Generates model data for reversed relationships, for all available models
778898
protected function generateReversedRelationships()
    {

        foreach ($this->context->output['models'] as $modelFromKey => $modelFrom) {

            foreach ($modelFrom['relationships']['normal'] as $relationName => $relationship) {

                // skip negative references for now, don't reverse them
                if ($relationship['negative']) {
                    $this->context->log(
                        "Skipped negative relationship for reversing (model: {$modelFromKey} to "
                        . "{$relationship['model']}, field: {$relationship['field']})"
                    );
                    continue;
                }

                // also skip any relationship we've overridden not to reverse
                if (array_get($relationship, 'prevent_reverse')) {
                    $this->context->log(
                        "Skipped relationship for reversing due to override (model: {$modelFromKey} to "
                        . "{$relationship['model']}, field: {$relationship['field']})"
                    );
                    continue;
                }

                // special case, referencing model is itself
                $selfReference     = ($modelFromKey == $relationship['model']);
                $partOfMultiple    = $this->multipleBelongsToRelationsBetweenModels($modelFromKey, $relationship['model']);
                $reverseType       = null;
                $reverseCount      = 0;
                $reverseForeignKey = null;


                // For non-cms_m_references relations, we need to be careful about
                // foreign keys not following the expected laravel convention
                // since they expect the name to be based on the model names, whereas
                // it is actually defined by the field name in the CMS module,
                // which conforms to the relation name of the OPPOSITE relation.
                //
                // Too tricky to determine automatically, so force a foreign key parameter
                // if required.
                if ($relationship['type'] !== Generator::RELATIONSHIP_BELONGS_TO_MANY) {

                    if (array_get($relationship, 'key')) {

                        $reverseForeignKey = $relationship['key'];

                    } elseif ($relationName !== camel_case($this->context->output['models'][ $relationship['model'] ]['name'])) {

                        $reverseForeignKey = $this->normalizeDb($relationName);
                    }
                }

                // determine type and one/many (count) for reverse relationship
                switch ($relationship['type']) {

                    case Generator::RELATIONSHIP_HAS_ONE:
                    case Generator::RELATIONSHIP_HAS_MANY:
                        $reverseType = Generator::RELATIONSHIP_BELONGS_TO;
                        break;

                    case Generator::RELATIONSHIP_BELONGS_TO:
                        // for single-entry modules, a hasOne will do
                        if ($this->data->rawData['modules'][ $modelFromKey ]['max_entries'] == 1) {
                            $reverseType  = Generator::RELATIONSHIP_HAS_ONE;
                            $reverseCount = 1;
                        } else {
                            $reverseType = Generator::RELATIONSHIP_HAS_MANY;
                        }
                        break;

                    case Generator::RELATIONSHIP_BELONGS_TO_MANY:
                        $reverseType = Generator::RELATIONSHIP_BELONGS_TO_MANY;
                        break;

                    // default omitted on purpose
                }

                // pluralize the name if configured to and it's a to many relationship
                $pluralizeName = (
                        $reverseCount !== 1
                    &&  config('pxlcms.generator.models.pluralize_reversed_relationship_names')
                    &&  ! $partOfMultiple
                    &&  (   ! $selfReference
                        ||  config('pxlcms.generator.models.pluralize_reversed_relationship_names_for_self_reference')
                        )
                );

                // name of the relationship reversed
                // default is name of the model referred to
                $baseName = $relationName;

                if ($partOfMultiple) {

                    $baseName = camel_case($modelFrom['name']) . ucfirst($baseName);

                } elseif ( ! $selfReference) {

                    $baseName = $modelFrom['name'];
                }

                if ($pluralizeName) {

                    $baseName = ($this->context->dutchMode) ? $this->dutchPluralize($baseName) : str_plural($baseName);
                }


                if (array_get($relationship, 'reverse_name')) {
                    // hard override is applied without any checks

                    $reverseName = $relationship['reverse_name'];

                } elseif ($selfReference || $partOfMultiple) {
                    // self-referencing is an exception, since using the model name won't be useful
                    // part of multiple belongsto is an exception, to avoid duplicates

                    $reverseName = $baseName
                                 . config('pxlcms.generator.models.relationship_reverse_postfix', 'Reverse');

                } else {

                    $reverseName = camel_case($baseName);
                }

                $reverseNameSnakeCase = snake_case($reverseName);

                // if already taken by an attribute, add custom string
                if (    in_array($reverseNameSnakeCase, $this->context->output['models'][ $relationship['model'] ]['normal_attributes'])
                    ||  in_array($reverseNameSnakeCase, $this->context->output['models'][ $relationship['model'] ]['translated_attributes'])
                    ||  in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['normal'])
                    ||  in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['image'])
                    ||  in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['file'])
                    ||  in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['checkbox'])
                ) {
                    $reverseName .= config('pxlcms.generator.models.relationship_fallback_postfix', 'Reference');
                }


                $this->context->output['models'][ $relationship['model'] ]['relationships']['reverse'][ $reverseName ] = [
                    'type'     => $reverseType,
                    'model'    => $modelFromKey,
                    'single'   => ($reverseCount == 1),
                    'count'    => $reverseCount,
                    'field'    => $relationship['field'],
                    'key'      => $reverseForeignKey,
                    'negative' => false,
                ];
            }
        }
    }
551690
def str_relationships_rev(self, goobj):
        """"""
        rel_cur = goobj.relationship_rev
        return "".join([self.rev2chr[r] if r in rel_cur else '.' for r in self.rels])
172715
def _load_data(self,
                   equities,
                   futures,
                   exchanges,
                   root_symbols,
                   equity_supplementary_mappings):
        
        # Set named identifier columns as indices, if provided.
        _normalize_index_columns_in_place(
            equities=equities,
            equity_supplementary_mappings=equity_supplementary_mappings,
            futures=futures,
            exchanges=exchanges,
            root_symbols=root_symbols,
        )

        futures_output = self._normalize_futures(futures)

        equity_supplementary_mappings_output = (
            self._normalize_equity_supplementary_mappings(
                equity_supplementary_mappings,
            )
        )

        exchanges_output = _generate_output_dataframe(
            data_subset=exchanges,
            defaults=_exchanges_defaults,
        )

        equities_output, equities_mappings = self._normalize_equities(
            equities,
            exchanges_output,
        )

        root_symbols_output = _generate_output_dataframe(
            data_subset=root_symbols,
            defaults=_root_symbols_defaults,
        )

        return AssetData(
            equities=equities_output,
            equities_mappings=equities_mappings,
            futures=futures_output,
            exchanges=exchanges_output,
            root_symbols=root_symbols_output,
            equity_supplementary_mappings=equity_supplementary_mappings_output,
        )
199963
def generate_base(model, model_dict, config, manifest, source_config,
                  provider, adapter=None):
    """"""
    if provider is None:
        raise dbt.exceptions.InternalException(
            "Invalid provider given to context: {}".format(provider))

    target_name = config.target_name
    target = config.to_profile_info()
    del target['credentials']
    target.update(config.credentials.serialize(with_aliases=True))
    target['type'] = config.credentials.type
    target.pop('pass', None)
    target['name'] = target_name

    adapter = get_adapter(config)

    context = {'env': target}

    pre_hooks = None
    post_hooks = None

    db_wrapper = DatabaseWrapper(adapter)

    context = dbt.utils.merge(context, {
        "adapter": db_wrapper,
        "api": {
            "Relation": db_wrapper.Relation,
            "Column": adapter.Column,
        },
        "column": adapter.Column,
        "config": provider.Config(model_dict, source_config),
        "database": config.credentials.database,
        "env_var": env_var,
        "exceptions": dbt.exceptions.wrapped_exports(model),
        "execute": provider.execute,
        "flags": dbt.flags,
        # TODO: Do we have to leave this in?
        "graph": manifest.to_flat_graph(),
        "log": log,
        "model": model_dict,
        "modules": {
            "pytz": get_pytz_module_context(),
            "datetime": get_datetime_module_context(),
        },
        "post_hooks": post_hooks,
        "pre_hooks": pre_hooks,
        "ref": provider.ref(db_wrapper, model, config, manifest),
        "return": _return,
        "schema": config.credentials.schema,
        "sql": None,
        "sql_now": adapter.date_function(),
        "source": provider.source(db_wrapper, model, config, manifest),
        "fromjson": fromjson,
        "tojson": tojson,
        "target": target,
        "try_or_compiler_error": try_or_compiler_error(model)
    })

    return context
460736
def admin_view_reverse_fk_links(modeladmin: ModelAdmin,
                                obj,
                                reverse_fk_set_field: str,
                                missing: str = "(None)",
                                use_str: bool = True,
                                separator: str = "<br>",
                                view_type: str = "change",
                                current_app: str = None) -> str:
    
    if not hasattr(obj, reverse_fk_set_field):
        return missing
    linked_objs = getattr(obj, reverse_fk_set_field).all()
    if not linked_objs:
        return missing
    first = linked_objs[0]
    app_name = first._meta.app_label.lower()
    model_name = first._meta.object_name.lower()
    viewname = "admin:{}_{}_{}".format(app_name, model_name, view_type)
    if current_app is None:
        current_app = modeladmin.admin_site.name
    links = []
    for linked_obj in linked_objs:
        # log.debug("linked_obj: {}", linked_obj)
        url = reverse(viewname, args=[linked_obj.pk], current_app=current_app)

        if use_str:
            label = escape(str(linked_obj))
        else:
            label = "{} {}".format(escape(linked_obj._meta.object_name),
                                   linked_obj.pk)
        links.append('<a href="{}">{}</a>'.format(url, label))
    # log.debug("links: {}", links)
    return separator.join(links)
37853
def _build_app_models(request, admin_apps, models_tuples, ensure_all_models=False):
    

    app_models = []
    for app_and_model, config in models_tuples:
        if app_and_model:
            app_label, model_name = app_and_model.split('.')

            for app in admin_apps:
                if app['app_label'] == app_label:
                    for model in app['models']:
                        if model['object_name'] == model_name:
                            try:
                                model['name'] = \
                                    config['name']
                            except KeyError:
                                pass

                            # Get each of the polymorphic types to allow addition.
                            model_class = apps.get_model(app_and_model)
                            model_admin = admin.site._registry[model_class]

                            if hasattr(model_admin, 'get_child_type_choices'):
                                model['polymorphic_classes'] = \
                                    model_admin.get_child_type_choices(
                                        request, 'add'
                                    )

                            # TODO: Fluent/polymorphic has a way of sorting child order which should be used instead
                            if 'default_poly_child' in config.keys():
                                ct = ContentType.objects.get_by_natural_key(
                                    *config['default_poly_child'].lower().split('.')
                                )
                                model.default_poly_child = ct.id

                            app_models.append(model)

                    break

    return app_models
779314
def _traverse_relationship_rev_objs(self, rel2dst2srcs, goobj_parent, goids_seen):
        """"""
        parent_id = goobj_parent.id
        goids_seen.add(parent_id)
        ##A self.go2obj[parent_id] = goobj_parent
        # Update goids_seen and go2obj with parent alt_ids
        for goid_altid in goobj_parent.alt_ids:
            goids_seen.add(goid_altid)
            ##A self.go2obj[goid_altid] = goobj_parent
        # Loop through children
        for reltype, recs in goobj_parent.relationship.items():
            if reltype in self.relationships:
                for relrev_obj in recs:
                    relrev_id = relrev_obj.id
                    rel2dst2srcs[relrev_id].add(parent_id)
                    # If child has not been seen, traverse
                    if relrev_id not in goids_seen:
                        ##F self._traverse_relrev_objs(rel2dst2srcs, relrev_obj, go2obj, goids_seen)
                        self._traverse_relationship_rev_objs(rel2dst2srcs, relrev_obj, goids_seen)
484124
def _get_all_relationships(self):
        """"""
        relationships_all = set()
        for goterm in self.go2obj.values():
            if goterm.relationship:
                relationships_all.update(goterm.relationship)
            if goterm.relationship_rev:
                relationships_all.update(goterm.relationship_rev)
        return relationships_all
1303785
def get_tables(self, models):
        '''
        
        '''
        return { obj._meta.db_table : obj for obj in
                models.__dict__.itervalues() if
                isinstance(obj, peewee.BaseModel) and
                len(obj._meta.fields) > 1
            }
580124
public function generateRenamedFields()
    {
        /* @var $oldModelState ModelState */
        /* @var $field Field */
        foreach ($this->keptModelKeys as $modelName) {
            $oldModelName = $this->getOldModelName($modelName);
            $meta = $this->newRegistry
                ->getModel($modelName)->getMeta();
            $oldModelState = $this->fromState->getModelState($oldModelName);

            $newModel = $this->newRegistry->getModel($modelName);

            $oldFieldKeys = $this->oldFieldKeys[$modelName];
            $newFieldKeys = $this->newFieldKeys[$modelName];

            $addedFields = array_diff($newFieldKeys, $oldFieldKeys);

            foreach ($addedFields as $addedField) {
                $field = $newModel->getMeta()->getField($addedField);
                $fieldDef = $this->deepDeconstruct($field);

                $removedFields = array_diff($oldFieldKeys, $newFieldKeys);
                foreach ($removedFields as $remField) {
                    $oldFieldDef = $this->deepDeconstruct(
                        $oldModelState->getFieldByName($remField)
                    );

                    if (!is_null($field->relation) &&
                        !is_null($field->relation->toModel) &&
                        isset($oldFieldDef['constructorArgs']['to'])
                    ) {
                        $oldRelTo = $oldFieldDef['constructorArgs']['to'];
                        if (in_array($oldRelTo, $this->renamedModels)) {
                            $oldFieldDef['constructorArgs']['to'] =
                                $this->getOldModelName($oldRelTo);
                        }
                    }

                    if ($fieldDef === $oldFieldDef) {
                        if (MigrationQuestion::hasFieldRenamed(
                            $this->asker,
                            $modelName,
                            $remField,
                            $addedField,
                            $field
                        )
                        ) {
                            $this->addOperation(
                                $meta->getAppName(),
                                RenameField::createObject(
                                    [
                                        'modelName' => $modelName,
                                        'oldName' => $remField,
                                        'newName' => $addedField,
                                    ]
                                )
                            );

                            // remove the old name and update with the new name.
                            $pos = array_search(
                                $remField,
                                $this->oldFieldKeys[$modelName]
                            );

                            array_splice(
                                $this->oldFieldKeys[$modelName],
                                $pos,
                                1,
                                [$addedField]
                            );
                            $this->renamedFields[$modelName][$addedField] = $remField;

                            break;
                        }
                    }
                }
            }
        }
    }
101218
def generate_model(self, model_name=None):
        """"""

        for i, c in enumerate(self._components):
            c.generate_model(model_name=model_name)
1183348
function generateModelFiles(db, next) {
    var q, templateTable, allNamingErrors = [];

    q = async.queue(function (task, workerCallback) {
        var output = getConfig('output.beautify') ? beautify(task.content, { indent_size: getConfig('output.indent'), preserve_newlines: getConfig('output.preserveNewLines') }) : task.content;
        fs.writeFile(path.join(getConfig('output.folder'), 'definition-files', getFileName(task.table)), output, workerCallback);
        if (getConfig('output.log')) { logger.info('(Created) File \'' + getFileName(task.table) + '\' is created for model \'' + getModelNameFor(task.table) + '\''); }
    }, 4);

    db.schemas(function (schema) {
        schema.tables(function (table) {
            var namingError = '';
            logger.debug('Now parsing table: %s', table.name());
            if (getSpecificConfig(table.name(), 'generate.hasManyThrough') && getSpecificConfig(table.name(), 'generate.belongsToMany')) {
                next(new Error('Configuration error: Both "generate.hasManyThrough" and "generate.belongsToMany" configuration is set to be true for table "' + table.schema().name() + '.' + table.name() + '". They cannot be true at the same time.'));
            }

            if (shouldSkip(table, 'table')) { return; }
            templateTable           = getTableOptions(table);
            table.columns(function (column) {
                templateTable.columns.push(getColumnDetails(column));
            });
            table.hasManies(function (hasMany) {
                if (shouldSkip(hasMany.referencesTable(), 'relation')) { return; }
                templateTable.hasManies.push(getHasManyDetails(hasMany));
            });
            table.hasManyThroughs(function (hasManyThrough) {
                if (getSpecificConfig(table.name(), 'generate.addRelationNameToManyToMany') && getSpecificConfig(table.name(), 'generate.addTableNameToManyToMany')) {
                    next(new Error('Configuration error: Both "generate.addRelationNameToManyToMany" and "generate.addTableNameToManyToMany" configuration is set to be true for table "' + table.schema().name() + '.' + table.name() + '". They cannot be true at the same time.'));
                }

                if (shouldSkip(hasManyThrough.referencesTable(), 'relation') || shouldSkip(hasManyThrough.through(), 'relation')) { return; }
                if (getSpecificConfig(table.name(), 'generate.hasManyThrough')) {
                    templateTable.hasManies.push(getHasManyDetails(hasManyThrough)); // has many throughs are deprecated after Sequelize 2.0 RC3
                }
                if (getSpecificConfig(table.name(), 'generate.belongsToMany')) {
                    templateTable.belongsToManies.push(getBelongsToManyDetails(hasManyThrough));
                }
            });
            table.foreignKeyConstraints(function (fkc) {
                if (shouldSkip(fkc.referencesTable(), 'relation')) { return; }
                templateTable.belongsTos.push(getBelongsToDetails(fkc));
            });
            templateTable.relations = templateTable.hasManies.concat(templateTable.belongsTos, templateTable.belongsToManies);

            namingError = validateNaming(templateTable);

            if (namingError) {
                allNamingErrors.push(namingError);
            }

            template('index', {
                table: templateTable,
                mainScript: path.join(getConfig('output.folder'), 'index.js'),
                warning: getConfig('output.warning'),
                dataTypeVariable: getSpecificConfig(table.name(), 'generate.dataTypeVariable')
            }, function (err, result) {
                if (err) { next(err); }
                q.push({content: result, table: table}, function (err) { if (err) { next(err); } });
            });
        });
    });

    q.drain = function () {
        if (allNamingErrors.length > 0) {
            next(new Error('There are naming errors. Either set "generate.addRelationNameToManyToMany" true in configuration or rename your relations.\n' + allNamingErrors.join('\n')));
        } else {
            next(null);
        }
    };
}
1112513
public function generateRenamedModels()
    {
        $addedModels = array_diff($this->newModelKeys, $this->oldModelKeys);

        /* @var $modelState ModelState */
        foreach ($addedModels as $addedModel) {
            $modelState = $this->toState->getModelState($addedModel);
            $meta = $this->newRegistry->getModel($addedModel)->getMeta();
            $modelDefinitionList = $this->getFieldsDefinitions(
                $modelState->fields
            );

            $removedModels = array_diff(
                $this->oldModelKeys,
                $this->newModelKeys
            );
            foreach ($removedModels as $removedModel) {
                $remModelState = $this->fromState->getModelState($removedModel);
                $remModelDefinitionList = $this->getFieldsDefinitions(
                    $remModelState->fields
                );

                if ($remModelDefinitionList == $modelDefinitionList) {
                    if (MigrationQuestion::hasModelRenamed(
                        $this->asker,
                        $removedModel,
                        $addedModel
                    )) {
                        $this->addOperation(
                            $meta->getAppName(),
                            RenameModel::createObject(
                                [
                                    'oldName' => $removedModel,
                                    'newName' => $addedModel,
                                ]
                            )
                        );

                        $this->renamedModels[$addedModel] = $removedModel;

                        // remove the old name and update with the new name.
                        $pos = array_search($removedModel, $this->oldModelKeys);

                        array_splice(
                            $this->oldModelKeys,
                            $pos,
                            1,
                            [$addedModel]
                        );

                        // you can stop here.
                        break;
                    }
                }
            }
        }
    }
1119331
def build_model_name(cls, name='modelName', output_name='output'):
        
        obj = cls(name)
        obj.exporter = 'generate_model_name'
        obj.output_name = output_name
        return obj
792856
def _clone_reverses(self, old_reverses):
        

        for ctype, reverses in old_reverses.items():
            for parts in reverses.values():
                sub_objs = parts[1]
                field_name = parts[0]

                attrs = {}
                for sub_obj in sub_objs:
                    if ctype != 'm2m' and not attrs:
                        field = sub_obj._meta.get_field(field_name)
                        attrs = {
                            field.column: getattr(self, field.rel.field_name)
                        }
                    sub_obj._clone(**attrs)

                if ctype == 'm2m':
                    setattr(self, field_name, sub_objs)
864780
def _models_generator():
    

    for app in apps.get_app_configs():
        for model in app.get_models():
            yield (str(model._meta.verbose_name).lower(), model)
            yield (str(model._meta.verbose_name_plural).lower(), model)
112989
def handle_model_generation(config, raml_resource):
    
    model_name = generate_model_name(raml_resource)
    try:
        return setup_data_model(config, raml_resource, model_name)
    except ValueError as ex:
        raise ValueError('{}: {}'.format(model_name, str(ex)))