If given some hints['instance'] that is saved in a db, use related
        fields from the same db. Otherwise if passed a class or instance to
        model, return the salesforce alias if it's a subclass of SalesforceModel.
12957
def db_for_write(self, model, **hints):
        
        if 'instance' in hints:
            db = hints['instance']._state.db
            if db:
                return db
        if getattr(model, '_salesforce_object', False):
            return self.sf_alias
598545
def formfield_for_foreignkey(self, db_field, *args, **kwargs):
        
        formfield = super(FluentLayoutsMixin, self).formfield_for_foreignkey(
            db_field, *args, **kwargs)
        if db_field.name == 'layout':
            formfield.queryset = formfield.queryset.for_model(self.model)
        return formfield
310798
def _query_db(self, mapping):
        
        model = self.models[mapping.get("table")]

        # Use primary key instead of the field mapped to SF Id
        fields = mapping.get("fields", {}).copy()
        if mapping["oid_as_pk"]:
            del fields["Id"]
        id_column = model.__table__.primary_key.columns.keys()[0]
        columns = [getattr(model, id_column)]

        for f in fields.values():
            columns.append(model.__table__.columns[f])
        lookups = mapping.get("lookups", {}).copy()
        for lookup in lookups.values():
            lookup["aliased_table"] = aliased(
                self.metadata.tables["{}_sf_ids".format(lookup["table"])]
            )
            columns.append(lookup["aliased_table"].columns.sf_id)

        query = self.session.query(*columns)
        if "record_type" in mapping and hasattr(model, "record_type"):
            query = query.filter(model.record_type == mapping["record_type"])
        if "filters" in mapping:
            filter_args = []
            for f in mapping["filters"]:
                filter_args.append(text(f))
            query = query.filter(*filter_args)
        for sf_field, lookup in lookups.items():
            # Outer join with lookup ids table:
            # returns main obj even if lookup is null
            key_field = get_lookup_key_field(lookup, sf_field)
            value_column = getattr(model, key_field)
            query = query.outerjoin(
                lookup["aliased_table"],
                lookup["aliased_table"].columns.id == value_column,
            )
            # Order by foreign key to minimize lock contention
            # by trying to keep lookup targets in the same batch
            lookup_column = getattr(model, key_field)
            query = query.order_by(lookup_column)
        self.logger.info(str(query))
        return query
1198607
def get_duplicated_model(self, class_inst, new_class_name):
        
        # Ref: http://www.cnblogs.com/Jerryshome/archive/2012/12/21/2827492.html
        attr_dict = {'__module__': self.module_name}
        for field in class_inst.__dict__['_meta'].fields:
            if self.is_relation_field_needed:
                attr_dict[field.name] = copy_field(field)
            elif not is_relation_field(field):
                attr_dict[field.name] = copy_field(field)
        # duplicated_model_class = type("Meta", (), {"abstract": True})
        duplicated_model_class = type(new_class_name, (models.Model,), attr_dict)
        # The following codes are not working
        # if hasattr(class_inst, "__str__"):
        #     setattr(duplicated_model_class, "__str__", getattr(class_inst, "__str__"))
        # if hasattr(class_inst, "__str__"):
        #     str_func = getattr(class_inst, "__str__")
        #     duplicated_model_class.__str__ = str_func
        return duplicated_model_class
292642
def get_proxy_field(self, instance):
        
        proxy_object = self.get_proxy_object(instance)
        if not proxy_object:
            return None
        return proxy_object.getField(self.name)
394771
async def add(self, *instances, using_db=None) -> None:
        
        if not instances:
            return
        if self.instance.id is None:
            raise OperationalError(
                "You should first call .save() on {model}".format(model=self.instance)
            )
        db = using_db if using_db else self.model._meta.db
        through_table = Table(self.field.through)
        select_query = (
            db.query_class.from_(through_table)
            .where(getattr(through_table, self.field.backward_key) == self.instance.id)
            .select(self.field.backward_key, self.field.forward_key)
        )
        query = db.query_class.into(through_table).columns(
            getattr(through_table, self.field.forward_key),
            getattr(through_table, self.field.backward_key),
        )

        if len(instances) == 1:
            criterion = getattr(through_table, self.field.forward_key) == instances[0].id
        else:
            criterion = getattr(through_table, self.field.forward_key).isin(
                [i.id for i in instances]
            )

        select_query = select_query.where(criterion)

        already_existing_relations_raw = await db.execute_query(str(select_query))
        already_existing_relations = {
            (r[self.field.backward_key], r[self.field.forward_key])
            for r in already_existing_relations_raw
        }

        insert_is_required = False
        for instance_to_add in instances:
            if instance_to_add.id is None:
                raise OperationalError(
                    "You should first call .save() on {model}".format(model=instance_to_add)
                )
            if (self.instance.id, instance_to_add.id) in already_existing_relations:
                continue
            query = query.insert(instance_to_add.id, self.instance.id)
            insert_is_required = True
        if insert_is_required:
            await db.execute_query(str(query))
1197832
static function getInstance($databaseNameOrResource = '*LOCAL', $userOrI5NamingFlag = '', $password = '', $extensionPrefix = '', $isPersistent = false, $forceNew = false)
    {
        // if we're forcing a new instance, close db conn first if exists.
        if ($forceNew && self::hasInstance() && isset(self::$instance->conn))
        {
            self::$instance->disconnect();
        }

        // if we're forcing a new instance, or an instance hasn't been created yet, create one
        if ($forceNew || self::$instance == NULL) {
            $toolkitService = __CLASS__;
            self::$instance = new $toolkitService($databaseNameOrResource, $userOrI5NamingFlag, $password, $extensionPrefix, $isPersistent);
        }

        if (self::$instance) {
            // instance exists
            return self::$instance;
        } else {
            // some problem
            return false;
        }
    }
446177
def get_instance_field(self, field_name):
        
        if not self.has_field(field_name):
            raise AttributeError('"%s" is not a field for the model "%s"' %
                                 (field_name, self.__class__.__name__))

        field = getattr(self, field_name)

        return field
417115
def field_singleton_schema(  # noqa: C901 (ignore complexity)
    field: Field,
    *,
    by_alias: bool,
    model_name_map: Dict[Type['main.BaseModel'], str],
    schema_overrides: bool = False,
    ref_prefix: Optional[str] = None,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
    

    ref_prefix = ref_prefix or default_prefix
    definitions: Dict[str, Any] = {}
    if field.sub_fields:
        return field_singleton_sub_fields_schema(
            field.sub_fields,
            by_alias=by_alias,
            model_name_map=model_name_map,
            schema_overrides=schema_overrides,
            ref_prefix=ref_prefix,
        )
    if field.type_ is Any:
        return {}, definitions  # no restrictions
    if is_callable_type(field.type_):
        raise SkipField(f'Callable {field.name} was excluded from schema since JSON schema has no equivalent type.')
    f_schema: Dict[str, Any] = {}
    if issubclass(field.type_, Enum):
        f_schema.update({'enum': [item.value for item in field.type_]})  # type: ignore
        # Don't return immediately, to allow adding specific types
    for field_name, schema_name in validation_attribute_to_schema_keyword.items():
        field_value = getattr(field.type_, field_name, None)
        if field_value is not None:
            if field_name == 'regex':
                field_value = field_value.pattern
            f_schema[schema_name] = field_value
    for type_, t_schema in field_class_to_schema_enum_enabled:
        if issubclass(field.type_, type_):
            f_schema.update(t_schema)
            break
    # Return schema, with or without enum definitions
    if f_schema:
        return f_schema, definitions
    for type_, t_schema in field_class_to_schema_enum_disabled:
        if issubclass(field.type_, type_):
            return t_schema, definitions
    # Handle dataclass-based models
    field_type = field.type_
    if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), main.BaseModel):
        field_type = cast(Type['dataclasses.DataclassType'], field_type)
        field_type = field_type.__pydantic_model__
    if issubclass(field_type, main.BaseModel):
        sub_schema, sub_definitions = model_process_schema(
            field_type, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix
        )
        definitions.update(sub_definitions)
        if not schema_overrides:
            model_name = model_name_map[field_type]
            definitions[model_name] = sub_schema
            return {'$ref': f'{ref_prefix}{model_name}'}, definitions
        else:
            return sub_schema, definitions
    raise ValueError(f'Value not declarable with JSON Schema, field: {field}')
266721
def remove_instance(self):
        
        with fields.FieldLock(self.related_field):
            related_pks = self()
            for pk in related_pks:

                # get the real related field
                related_instance = self.related_field._model(pk)
                related_field = getattr(related_instance, self.related_field.name)

                # check if we have a dedicated remove method
                remover = getattr(related_field, '_related_remover', None)

                # then remove the instance from the related field
                if remover is not None:
                    # if we have a remover method, it wants the instance as argument
                    # (the related field may be a set/list/sorted_set)
                    getattr(related_field, remover)(self.instance._pk)
                else:
                    # no remover method, simple delete the field
                    related_field.delete()
331789
def add_instance(model, _commit=True, **kwargs):
    
    try:
        model = get_model(model)
    except ImportError:
        return None

    instance = model(**kwargs)
    db.session.add(instance)

    try:
        if _commit:
            db.session.commit()
        else:
            db.session.flush()
        return instance.id
    except IntegrityError:
        db.session.rollback()
        return
703051
def get_alias(self):
        
        alias = None
        if self.alias:
            alias = self.alias
        elif self.auto_alias:
            alias = self.auto_alias

        if self.table and self.table.prefix_fields:
            field_prefix = self.table.get_field_prefix()
            if alias:
                alias = '{0}__{1}'.format(field_prefix, alias)
            else:
                alias = '{0}__{1}'.format(field_prefix, self.name)

        return alias
272611
def transform_model(cls) -> None:
    
    if cls.name != "Model":
        appname = "models"
        for mcls in cls.get_children():
            if isinstance(mcls, ClassDef):
                for attr in mcls.get_children():
                    if isinstance(attr, Assign):
                        if attr.targets[0].name == "app":
                            appname = attr.value.value

        mname = "{}.{}".format(appname, cls.name)
        MODELS[mname] = cls

        for relname, relval in FUTURE_RELATIONS.get(mname, []):
            cls.locals[relname] = relval

        for attr in cls.get_children():
            if isinstance(attr, Assign):
                try:
                    attrname = attr.value.func.attrname
                except AttributeError:
                    pass
                else:
                    if attrname in ["ForeignKeyField", "ManyToManyField"]:
                        tomodel = attr.value.args[0].value
                        relname = ""
                        if attr.value.keywords:
                            for keyword in attr.value.keywords:
                                if keyword.arg == "related_name":
                                    relname = keyword.value.value

                        if not relname:
                            relname = cls.name.lower() + "s"

                        # Injected model attributes need to also have the relation manager
                        if attrname == "ManyToManyField":
                            relval = [
                                attr.value.func,
                                MANAGER.ast_from_module_name("tortoise.fields").lookup(
                                    "ManyToManyRelationManager"
                                )[1][0],
                            ]
                        else:
                            relval = [
                                attr.value.func,
                                MANAGER.ast_from_module_name("tortoise.fields").lookup(
                                    "RelationQueryContainer"
                                )[1][0],
                            ]

                        if tomodel in MODELS:
                            MODELS[tomodel].locals[relname] = relval
                        else:
                            FUTURE_RELATIONS.setdefault(tomodel, []).append((relname, relval))

    cls.locals["_meta"] = [
        MANAGER.ast_from_module_name("tortoise.models").lookup("MetaInfo")[1][0].instantiate_class()
    ]
    if "id" not in cls.locals:
        cls.locals["id"] = [nodes.ClassDef("id", None)]
54222
def is_sf_database(db, model=None):
    """"""
    from django.db import connections
    if db is None:
        return getattr(model, '_salesforce_object', False)
    engine = connections[db].settings_dict['ENGINE']
    return engine == 'salesforce.backend' or connections[db].vendor == 'salesforce'
1053131
private void matchJoinedFields(JoinInfo joinInfo, QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException {
		for (FieldType fieldType : tableInfo.getFieldTypes()) {
			// if this is a foreign field and its foreign field is the same as the other's id
			FieldType foreignRefField = fieldType.getForeignRefField();
			if (fieldType.isForeign() && foreignRefField.equals(joinedQueryBuilder.tableInfo.getIdField())) {
				joinInfo.localField = fieldType;
				joinInfo.remoteField = foreignRefField;
				return;
			}
		}
		// if this other field is a foreign field and its foreign-id field is our id
		for (FieldType fieldType : joinedQueryBuilder.tableInfo.getFieldTypes()) {
			if (fieldType.isForeign() && fieldType.getForeignIdField().equals(idField)) {
				joinInfo.localField = idField;
				joinInfo.remoteField = fieldType;
				return;
			}
		}

		throw new SQLException("Could not find a foreign " + tableInfo.getDataClass() + " field in "
				+ joinedQueryBuilder.tableInfo.getDataClass() + " or vice versa");
	}
1363678
def alias_field(model, field):
    
    for part in field.split(LOOKUP_SEP)[:-1]:
        model = associate_model(model,part)
    return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1]
1196329
def is_inheritance_parent(self, field):
        '''
        
        '''
        return (
            isinstance(field, related.OneToOneField) and
            field.primary_key and
            issubclass(field.model, get_remote_field_to(field))
        )