| 1 | """Statistical summary of store statements mixin""" |
| 2 | from sqlalchemy.orm.session import Session |
| 3 | from sqlalchemy.sql import func |
| 4 | |
| 5 | |
| 6 | def get_group_by_count(session, group_by_column): |
| 7 | """ |
| 8 | Construct SQL query to get counts for distinct values using GROUP BY. |
| 9 | |
| 10 | Args: |
| 11 | session (~sqlalchemy.orm.session.Session): session to query in |
| 12 | group_by_column (~sqlalchemy.schema.Column): column to group by |
| 13 | |
| 14 | Returns: |
| 15 | dict: dictionary mapping from value to count |
| 16 | """ |
| 17 | return dict( |
| 18 | session.query( |
| 19 | group_by_column, |
| 20 | func.count(group_by_column) |
| 21 | ).group_by(group_by_column).all() |
| 22 | ) |
| 23 | |
| 24 | |
| 25 | class StatisticsMixin: |
| 26 | ''' Has methods for statistics on stores ''' |
| 27 | def statistics(self, asserted_statements=True, literals=True, types=True): |
| 28 | """Store statistics.""" |
| 29 | statistics = { |
| 30 | "store": dict(total_num_statements=len(self)), |
| 31 | } |
| 32 | |
| 33 | with self.engine.connect() as connection: |
| 34 | session = Session(bind=connection) |
| 35 | if asserted_statements: |
| 36 | table = self.tables["asserted_statements"] |
| 37 | group_by_column = table.c.predicate |
| 38 | statistics["asserted_statements"] = get_group_by_count(session, group_by_column) |
| 39 | if literals: |
| 40 | table = self.tables["literal_statements"] |
| 41 | group_by_column = table.c.predicate |
| 42 | statistics["literals"] = get_group_by_count(session, group_by_column) |
| 43 | if types: |
| 44 | table = self.tables["type_statements"] |
| 45 | group_by_column = table.c.klass |
| 46 | statistics["types"] = get_group_by_count(session, group_by_column) |
| 47 | |
| 48 | return statistics |