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__(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, 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__(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__(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__(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__(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__(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__(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 sql_model(self, model): sql_model = getattr(model, '_sql_model', None) if not sql_model: meta = model._meta fields = {'__tablename__': meta.table_name} for field in model._meta.dfields.values(): fields[field.store_name] = field.sql_alchemy_column() sql_model = DeclarativeMeta(meta.name, (Base,), fields) model._sql_model = sql_model sql_model._meta = meta return sql_model
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): 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, 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
async def save_instances( instances: Iterable[DeclarativeMeta], *, cls: DeclarativeMeta, connection: ConnectionType, is_mysql: bool) -> List[int]: columns_names = list(cls.columns_fields_names()) primary_key = await get_primary_key(table=cls.__table__) primary_key_column_index = columns_names.index(primary_key) columns_names.pop(primary_key_column_index) unique_columns_names = await get_unique_columns_names(cls.__table__) returning_columns_names = [primary_key] def record_without_id(instance: DeclarativeMeta ) -> RecordType: res = list(instance.record) res.pop(primary_key_column_index) return tuple(res) records = map(record_without_id, instances) resp = await insert_returning( table_name=cls.__tablename__, columns_names=columns_names, unique_columns_names=unique_columns_names, returning_columns_names=returning_columns_names, records=records, merge=True, connection=connection, is_mysql=is_mysql) return [row[0] for row in resp]
def __new__(cls, name, bases, d): tablename = d.get('__tablename__') has_pks = any(v.primary_key for k, v in d.items() if isinstance(v, Column)) # generate a table name automatically if it's missing and the # class dictionary declares a primary key. We cannot always # attach a primary key to support model inheritance that does # not use joins. We also don't want a table name if a whole # table is defined if not tablename and d.get('__table__') is None and has_pks: def _join(match): word = match.group() if len(word) > 1: return ('_%s_%s' % (word[:-1], word[-1])).lower() return '_' + word.lower() d['__tablename__'] = cls._camelcase_re.sub(_join, name).lstrip('_') if '__table_cls__' not in d: d['__table_cls__'] = Table return DeclarativeMeta.__new__(cls, name, bases, d)
def __new__(cls, cls_name, cls_bases, cls_dict): if cls_dict.get("__type_name__", None) is None: cls_dict["__type_name__"] = cls_name if cls_dict.get("_type_info", None) is None: cls_dict["_type_info"] = _type_info = TypeInfo() for k, v in cls_dict.items(): if (not k.startswith('__')) and isinstance(v, Column): _type_info[k] = _process_item(v) table = cls_dict.get('__table__', None) if not (table is None): for c in table.c: _type_info[c.name] = _process_item(c) # mixin inheritance for b in cls_bases: for k,v in vars(b).items(): if isinstance(v, Column): _type_info[k] = _process_item(v) # same table inheritance for b in cls_bases: table = getattr(b, '__table__', None) if not (table is None): for c in table.c: _type_info[c.name] = _process_item(c) return DeclarativeMeta.__new__(cls, cls_name, cls_bases, cls_dict)
def __new__(cls, classname, bases, dict_): tablename = dict_.get('__tablename__') if not tablename and not dict_.get('__table__') \ and _DeclarativeMeta.has_primary_key(dict_): dict_['__tablename__'] = strings.pluralize( strings.snakecase(classname)) return DeclarativeMeta.__new__(cls, classname, bases, dict_)
def __new__(mcs, name, bases, dct): # Set __events__ to expected default so that it's updatable when # initializing. E.g. if class definition sets __events__=None but # defines decorated events, then we want the final __events__ attribute # to reflect the registered events. If set to anything that's # non-empty/non-dict will lead to an error if decorated events defined. if not dct.get('__events__'): dct['__events__'] = {} if '__bind_key__' not in dct: base_dcts = [dct] + [base.__dict__ for base in bases] for base in base_dcts: if '__bind_key__' in base: dct['__bind_key__'] = base['__bind_key__'] break cls = DeclarativeMeta.__new__(mcs, name, bases, dct) # Determine if should set __tablename__. # This is being done after DeclarativeMeta.__new__() # as the class is needed to accommodate @declared_attr columns. if should_set_tablename(cls): # Set to underscore version of class name. cls.__tablename__ = camelcase_to_underscore(name) return cls
def build_schema(base: DeclarativeMeta, enable_subscription: bool = False) -> GraphQLSchema: """ Args: base: enable_subscription: Returns: :class:`graphql:graphql.type.GraphQLSchema` """ queries: GraphQLFieldMap = {} mutations: GraphQLFieldMap = {} objects: Objects = {} inputs: Inputs = {} for model in base.__subclasses__(): build_queries(model, objects, queries, inputs) build_mutations(model, objects, mutations, inputs) return GraphQLSchema( GraphQLObjectType("Query", queries), GraphQLObjectType("Mutation", mutations), GraphQLObjectType("Subscription", {}) if enable_subscription else None, )
def __new__(cls, cls_name, cls_bases, cls_dict): if cls_dict.get("__type_name__", None) is None: cls_dict["__type_name__"] = cls_name if cls_dict.get("_type_info", None) is None: cls_dict["_type_info"] = _type_info = TypeInfo() # mixin inheritance for b in cls_bases: for k,v in vars(b).items(): if _is_interesting(k,v): _type_info[k] = _process_item(v) # same table inheritance for b in cls_bases: table = getattr(b, '__table__', None) if not (table is None): for c in table.c: _type_info[c.name] = _process_item(c) # include from table table = cls_dict.get('__table__', None) if not (table is None): for c in table.c: _type_info[c.name] = _process_item(c) # own attributes for k, v in cls_dict.items(): if _is_interesting(k,v): _type_info[k] = _process_item(v) return DeclarativeMeta.__new__(cls, cls_name, cls_bases, cls_dict)
def __new__(cls, name, bases, d): # if tablename is set explicitly, move it to the cache attribute so # that future subclasses still have auto behavior if '__tablename__' in d: d['_cached_tablename'] = d.pop('__tablename__') return DeclarativeMeta.__new__(cls, name, bases, d)
def __new__(cls, cls_name, cls_bases, cls_dict): if cls_dict.get("__type_name__", None) is None: cls_dict["__type_name__"] = cls_name if cls_dict.get("_type_info", None) is None: cls_dict["_type_info"] = _type_info = TypeInfo() # mixin inheritance for b in cls_bases: for k, v in vars(b).items(): if _is_interesting(k, v): _type_info[k] = _process_item(v) # same table inheritance for b in cls_bases: table = getattr(b, '__table__', None) if not (table is None): for c in table.c: _type_info[c.name] = _process_item(c) # include from table table = cls_dict.get('__table__', None) if not (table is None): for c in table.c: _type_info[c.name] = _process_item(c) # own attributes for k, v in cls_dict.items(): if _is_interesting(k, v): _type_info[k] = _process_item(v) return DeclarativeMeta.__new__(cls, cls_name, cls_bases, cls_dict)
def __new__(cls, cls_name, cls_bases, cls_dict): if cls_dict.get("__type_name__", None) is None: cls_dict["__type_name__"] = cls_name if cls_dict.get("_type_info", None) is None: parse_cls_dict(cls_dict) return DeclarativeMeta.__new__(cls, cls_name, cls_bases, cls_dict)
def __new__(cls, name, bases, dictionary): if '__mapper_args__' in dictionary.keys(): dictionary['__mapper_args__']['polymorphic_identity'] = to_unicode( name) else: dictionary['__mapper_args__'] = dict( polymorphic_identity=to_unicode(name)) return DeclarativeMeta.__new__(cls, name, bases, dictionary)
def __new__(self, name, bases, attrs): cls = DeclarativeMeta.__new__(self, name, bases, attrs) for base in bases: if issubclass(base, CacheMixinBase) and hasattr(cls, '_hook'): cls._hook.add_table(cls) break return cls
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) 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 __new__(metatype, name, bases, namespace): meta = namespace.pop('meta', None) if not meta: return DeclarativeMeta.__new__(metatype, name, bases, namespace) elif not isinstance(meta, dict): meta = dict(meta.__dict__) schema = meta.pop('schema') if not isinstance(schema, Schema): schema = Schema(schema) namespace['_spire_schema'] = schema namespace['metadata'] = schema.metadata abstract = meta.pop('abstract', False) tablename = meta.pop('tablename', None) mapper_params = {} for param in MAPPER_PARAMS: if param in meta: mapper_params[param] = meta.pop(param) if mapper_params: namespace['__mapper_args__'] = mapper_params table_args = [] for param in ('constraints', 'indexes'): if param in meta: table_args.extend(meta.pop(param)) if meta: meta = dict((key, value) for key, value in meta.iteritems() if key[0] != '_') if meta: table_args.append(meta) if table_args: namespace['__table_args__'] = tuple(table_args) if not tablename: tablename = name.lower() if '__tablename__' not in namespace and not abstract: namespace['__tablename__'] = tablename model = DeclarativeMeta.__new__(metatype, name, bases, namespace) return model
def __new__(metatype, name, bases, namespace): meta = namespace.pop("meta", None) if not meta: return DeclarativeMeta.__new__(metatype, name, bases, namespace) elif not isinstance(meta, dict): meta = dict(meta.__dict__) schema = meta.pop("schema") if not isinstance(schema, Schema): schema = Schema(schema) namespace["_spire_schema"] = schema namespace["metadata"] = schema.metadata abstract = meta.pop("abstract", False) tablename = meta.pop("tablename", None) mapper_params = {} for param in MAPPER_PARAMS: if param in meta: mapper_params[param] = meta.pop(param) if mapper_params: namespace["__mapper_args__"] = mapper_params table_args = [] for param in ("constraints", "indexes"): if param in meta: table_args.extend(meta.pop(param)) if meta: meta = dict((key, value) for key, value in meta.iteritems() if key[0] != "_") if meta: table_args.append(meta) if table_args: namespace["__table_args__"] = tuple(table_args) if not tablename: tablename = name.lower() if "__tablename__" not in namespace and not abstract: namespace["__tablename__"] = tablename model = DeclarativeMeta.__new__(metatype, name, bases, namespace) return model
def __new__(self, name, bases, attrs): cls = DeclarativeMeta.__new__(self, name, bases, attrs) from core import CacheMixinBase for base in bases: if issubclass(base, CacheMixinBase) and hasattr(cls, "_hook"): cls._hook.add(cls) break return cls
def construct_bare(class_: DeclarativeMeta) -> "SQLClass": """ Returns an object of type *class_*, without invoking the class' constructor. """ obj = class_.__new__(class_) manager = getattr(class_, instrumentation.ClassManager.MANAGER_ATTR) setattr(obj, manager.STATE_ATTR, state.InstanceState(obj, manager)) return obj
def __new__(cls, name, bases, d): # if tablename is set explicitly, move it to the cache attribute so # that future subclasses still have auto behavior if '__tablename__' in d: table = d['__tablename__'] if not isinstance(table, declared_attr): d.pop('__tablename__') d['_cached_tablename'] = table return DeclarativeMeta.__new__(cls, name, bases, d)
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 __new__(cls, name, bases, d): if _should_set_tablename(bases, d): def _join(match): word = match.group() if len(word) > 1: return ('_%s_%s' % (word[:-1], word[-1])).lower() return '_' + word.lower() d['__tablename__'] = _camelcase_re.sub(_join, name).lstrip('_') return DeclarativeMeta.__new__(cls, name, bases, d)
def __new__(cls, name, bases, dct): # set __tablename__ (if not defined) to underscore version of class name if not dct.get("__tablename__") and not dct.get("__table__") is not None and has_primary_key(dct): dct["__tablename__"] = camelcase_to_underscore(name) # set __events__ to expected default so that it's updatable when initializing # e.g. if class definition sets __events__=None but defines decorated events, # then we want the final __events__ attribute to reflect the registered events. # if set to anything that's non-empty/non-dict will lead to an error if decorated events defined if not dct.get("__events__"): dct["__events__"] = {} return DeclarativeMeta.__new__(cls, name, bases, dct)
def __new__(cls, name, bases, d): tablename = d.get('__tablename__') # generate a table name automatically if it's missing and the # class dictionary declares a primary key. We cannot always # attach a primary key to support model inheritance that does # not use joins. We also don't want a table name if a whole # table is defined if not tablename and d.get('__table__') is None and _defines_primary_key(d): def _join(match): word = match.group() if len(word) > 1: return ('_%s_%s' % (word[:-1], word[-1])).lower() return '_' + word.lower() d['__tablename__'] = _camelcase_re.sub(_join, name).lstrip('_') return DeclarativeMeta.__new__(cls, name, bases, d)
def __new__(mcs, name, bases, dct): # Determine if primary key is defined for dct or any of its bases. base_dcts = [dct] + [base.__dict__ for base in bases] if (not dct.get('__tablename__') and dct.get('__table__') is None and any([has_primary_key(base) for base in base_dcts])): # Set to underscore version of class name. dct['__tablename__'] = camelcase_to_underscore(name) # Set __events__ to expected default so that it's updatable when # initializing. E.g. if class definition sets __events__=None but # defines decorated events, then we want the final __events__ attribute # to reflect the registered events. If set to anything that's # non-empty/non-dict will lead to an error if decorated events defined. if not dct.get('__events__'): dct['__events__'] = {} return DeclarativeMeta.__new__(mcs, name, bases, dct)
def __new__(cls, name, bases, d): if d.get("__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]) return DeclarativeMeta.__new__(cls, name, bases, d)
def __new__(cls, name, bases, d): if '__tablename__' not in d and '__table__' not in d and '__abstract__' not in d: d['__tablename__'] = get_table_name(name) default_table_args = d.pop('__default_table_args__', BaseModel.__default_table_args__) table_args = d.pop('__table_args__', {}) if isinstance(table_args, dict): table_args = merge_dicts(default_table_args, table_args) elif isinstance(table_args, tuple): table_args = list(table_args) if isinstance(table_args[-1], dict): table_args[-1] = merge_dicts(default_table_args, table_args[-1]) else: table_args.append(default_table_args) table_args = tuple(table_args) d['__table_args__'] = table_args return DeclarativeMeta.__new__(cls, name, bases, d)
def __new__(cls, name, bases, d): tablename = d.get('__tablename__') # generate a table name automatically if it's missing and the # class dictionary declares a primary key. We cannot always # attach a primary key to support model inheritance that does # not use joins. We also don't want a table name if a whole # table is defined if not tablename and not d.get('__table__') and \ _defines_primary_key(d): def _join(match): word = match.group() if len(word) > 1: return ('_%s_%s' % (word[:-1], word[-1])).lower() return '_' + word.lower() d['__tablename__'] = _camelcase_re.sub(_join, name).lstrip('_') return DeclarativeMeta.__new__(cls, name, bases, d)
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 __new__(cls, name, bases, d): if _should_set_tablename(bases, d): def _camel_to_snake(name): """ Convert a CamelCase string to snake_case """ if not name: return "" if len(name) == 1: return name.lower() return (name[0] + "".join([("_" + c) \ if prev.islower() and c.isupper() \ or prev.islower() and c.isdigit() and (next.isdigit() or next.isupper()) \ or (prev.isdigit() or prev.isupper()) and c.isupper() and next.islower() \ else c \ for prev, c, next in zip(name[:-2], name[1:-1], name[2:])]) + ("_" + name[-1] if name[-2:-1].islower() and (name[-1].isupper() or name[-1].isdigit()) else name[-1])).lower() d['__tablename__'] = _camel_to_snake(name) return DeclarativeMeta.__new__(cls, name, bases, d)