Results of a SQL query. Can access rows listwise, or by string value of leftmost column.
| 86 | |
| 87 | |
| 88 | class ResultSet(list, ColumnGuesserMixin): |
| 89 | """ |
| 90 | Results of a SQL query. |
| 91 | |
| 92 | Can access rows listwise, or by string value of leftmost column. |
| 93 | """ |
| 94 | def __init__(self, sqlaproxy, sql, config): |
| 95 | self.keys = sqlaproxy.keys() |
| 96 | self.sql = sql |
| 97 | self.config = config |
| 98 | self.limit = config.autolimit |
| 99 | style_name = config.style |
| 100 | self.style = prettytable.__dict__[style_name.upper()] |
| 101 | if sqlaproxy.returns_rows: |
| 102 | if self.limit: |
| 103 | list.__init__(self, sqlaproxy.fetchmany(size=self.limit)) |
| 104 | else: |
| 105 | list.__init__(self, sqlaproxy.fetchall()) |
| 106 | self.field_names = unduplicate_field_names(self.keys) |
| 107 | self.pretty = prettytable.PrettyTable(self.field_names) |
| 108 | if not config.autopandas: |
| 109 | for row in self[:config.displaylimit or None]: |
| 110 | self.pretty.add_row(row) |
| 111 | self.pretty.set_style(self.style) |
| 112 | else: |
| 113 | list.__init__(self, []) |
| 114 | self.pretty = None |
| 115 | def _repr_html_(self): |
| 116 | _cell_with_spaces_pattern = re.compile(r'(<td>)( {2,})') |
| 117 | if self.pretty: |
| 118 | result = self.pretty.get_html_string() |
| 119 | result = _cell_with_spaces_pattern.sub(_nonbreaking_spaces, result) |
| 120 | if self.config.displaylimit and len(self) > self.config.displaylimit: |
| 121 | result = '%s\n<span style="font-style:italic;text-align:center;">%d rows, truncated to displaylimit of %d</span>' % ( |
| 122 | result, len(self), self.config.displaylimit) |
| 123 | return result |
| 124 | else: |
| 125 | return None |
| 126 | def __str__(self, *arg, **kwarg): |
| 127 | return str(self.pretty or '') |
| 128 | def __getitem__(self, key): |
| 129 | """ |
| 130 | Access by integer (row position within result set) |
| 131 | or by string (value of leftmost column) |
| 132 | """ |
| 133 | try: |
| 134 | return list.__getitem__(self, key) |
| 135 | except TypeError: |
| 136 | result = [row for row in self if row[0] == key] |
| 137 | if not result: |
| 138 | raise KeyError(key) |
| 139 | if len(result) > 1: |
| 140 | raise KeyError('%d results for "%s"' % (len(result), key)) |
| 141 | return result[0] |
| 142 | def dict(self): |
| 143 | "Returns a dict built from the result set, with column names as keys" |
| 144 | return dict(zip(self.keys, zip(*self))) |
| 145 |