Debian Codegraph @

gavo/grammars/rowsetgrammar.py

raw
1 """
2 A grammar that takes standard tuples as input and turns them into rows
3 of a table.
4 """
5
6 #c Copyright 2008-2025, the GAVO project <[email protected]>
7 #c
8 #c This program is free software, covered by the GNU GPL. See the
9 #c COPYING file in the source distribution.
10
11
12 from gavo import base
13 from gavo.grammars import common
14
15 class RowsetIterator(common.RowIterator):
16 """is a row iterator over a sequence of tuples.
17 """
18 def _decodeRow(self, row):
19 # a bit crazy to avoid having to rebuild every row in the "normal" case
20 # of ASCII input
21 newFields = {}
22 for ind, r in enumerate(row):
23 if isinstance(r, bytes) and max(r)>'~':
24 newFields[ind] = r.decode(self.grammar.enc)
25 newRow = []
26 if newFields:
27 for ind, v in enumerate(row):
28 if ind in newFields:
29 newRow.append(newFields[ind])
30 else:
31 newRow.append(v)
32 return tuple(newRow)
33 else:
34 return row
35
36 def _iterRows(self):
37 colNames = self.grammar.names
38 for row in self.sourceToken:
39 if self.grammar.enc:
40 row = self._decodeRow(row)
41 yield dict(list(zip(colNames, row)))
42 self.grammar = None
43
44
45 class RowsetGrammar(common.Grammar):
46 """A grammar handling sequences of tuples.
47
48 To add semantics to the field, it must know the "schema" of the
49 data. This is defined via the table it is supposed to get the input
50 from.
51
52 This grammar probably is only useful for internal purposes.
53 """
54 name_ = "rowsetGrammar"
55 rowIterator = RowsetIterator
56
57 _fieldsFrom = base.ReferenceAttribute("fieldsFrom",
58 description="the table defining the columns in the tuples.", copyable=True)
59
60 def onElementComplete(self):
61 super().onElementComplete()
62 self.names = [c.name for c in self.fieldsFrom]