sqlalchemy.inspection.inspect - python examples

Here are the examples of the python api sqlalchemy.inspection.inspect taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5 Examples 7

3 View Complete Implementation : __init__.py
Copyright Mozilla Public License 2.0
Author : AnyBlok
def has_sqlalchemy_fields(base):
    for p in base.__dict__.keys():
        attr = base.__dict__[p]
        if inspection.inspect(attr, raiseerr=False) is not None:
            return True

    return False

3 View Complete Implementation : BBDD.py
Copyright Apache License 2.0
Author : BBVA
def query_to_dict(rset):
    result = defaultdict(list)
    for obj in rset:
        instance = inspect(obj)
        for key, x in instance.attrs.items():
            result[key].append(x.value)
    return result

3 View Complete Implementation : __init__.py
Copyright MIT License
Author : instacart
    @clastmethod
    def get(cls, *key):
        session = Session()

        filter = {str(k.name): v for k, v in dict(zip(inspect(cls).primary_key, key)).items()}
        instance = session.query(cls).filter_by(**filter).first()
        session.close()
        return instance

2 View Complete Implementation : query.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : TheChymera
def get_for_protocolize(db_path, clast_name, code):
	"""Return a dataframe containing a specific entry from a given clast name, joined with its related tables up to three levels down.
	"""
	session, engine = load_session(db_path)
	cols = []
	joins = []
	clastobject = ALLOWED_CLastES[clast_name]
	insp = sqlalchemy.inspection.inspect(clastobject)
	for name, col in insp.columns.items():
		cols.append(col.label(name))
	for name, rel in insp.relationships.items():
		alias = aliased(rel.mapper.clast_, name=name)
		joins.append((alias, rel.clast_attribute))
		for col_name, col in sqlalchemy.inspection.inspect(rel.mapper).columns.items():
			#the id column causes double entries, as it is mapped once on the parent table (related_table_id) and once on the child table (table_id)
			if col.key != "id":
				aliased_col = getattr(alias, col.key)
				cols.append(aliased_col.label("{}_{}".format(name, col_name)))

		sub_insp = sqlalchemy.inspection.inspect(rel.mapper.clast_)
		for sub_name, sub_rel in sub_insp.relationships.items():
			if "contains" not in sub_name:
				sub_alias = aliased(sub_rel.mapper.clast_, name=name+"_"+sub_name)
				joins.append((sub_alias, sub_rel.clast_attribute))
				for sub_col_name, sub_col in sqlalchemy.inspection.inspect(sub_rel.mapper).columns.items():
					#the id column causes double entries, as it is mapped once on the parent table (related_table_id) and once on the child table (table_id)
					if sub_col.key != "id":
						sub_aliased_col = getattr(sub_alias, sub_col.key)
						cols.append(sub_aliased_col.label("{}_{}_{}".format(name, sub_name, sub_col_name)))

	sql_query = session.query(*cols).select_from(clastobject)
	for join in joins:
		sql_query = sql_query.outerjoin(*join)
	sql_query = sql_query.filter(clastobject.code == code)

	mystring = sql_query.statement
	mydf = pd.read_sql_query(mystring,engine)

	session.close()
	engine.dispose()
	return mydf

0 View Complete Implementation : alchemy.py
Copyright MIT License
Author : miLibris
    def apply_nested_fields(self, data, obj):
        nested_fields_to_apply = []
        nested_fields = get_nested_fields(self.resource.schema, model_field=True)
        for key, value in data.items():
            if key in nested_fields:
                nested_field_inspection = inspect(getattr(obj.__clast__, key))

                if not isinstance(nested_field_inspection, QueryableAttribute):
                    raise InvalidType("Unrecognized nested field type: not a queryable attribute.")

                if isinstance(nested_field_inspection.property, RelationshipProperty):
                    nested_model = getattr(obj.__clast__, key).property.mapper.clast_

                    if isinstance(value, list):
                        nested_objects = []

                        for identifier in value:
                            nested_object = nested_model(**identifier)
                            nested_objects.append(nested_object)

                        nested_fields_to_apply.append({'field': key, 'value': nested_objects})
                    else:
                        nested_fields_to_apply.append({'field': key, 'value': nested_model(**value)})
                elif isinstance(nested_field_inspection.property, ColumnProperty):
                    nested_fields_to_apply.append({'field': key, 'value': value})
                else:
                    raise InvalidType("Unrecognized nested field type: not a RelationshipProperty or ColumnProperty.")

        for nested_field in nested_fields_to_apply:
            setattr(obj, nested_field['field'], nested_field['value'])