summaryrefslogtreecommitdiff
path: root/src/tablib/packages/dbfpy3/record.py
blob: d30147699fdda746cc256056898e2d37ab1a0d79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""DBF record definition.

"""
"""History (most recent first):
11-feb-2007 [als]   __repr__: added special case for invalid field values
10-feb-2007 [als]   added .rawFromStream()
30-oct-2006 [als]   fix record length in .fromStream()
04-jul-2006 [als]   added export declaration
20-dec-2005 [yc]    DbfRecord.write() -> DbfRecord._write();
                    added delete() method.
16-dec-2005 [yc]    record definition moved from `dbf`.
"""

__version__ = "$Revision: 1.7 $"[11:-2]
__date__ = "$Date: 2007/02/11 09:05:49 $"[7:-2]

__all__ = ["DbfRecord"]

import sys

from . import utils

class DbfRecord(object):
    """DBF record.

    Instances of this class shouldn't be created manualy,
    use `dbf.Dbf.newRecord` instead.

    Class implements mapping/sequence interface, so
    fields could be accessed via their names or indexes
    (names is a preffered way to access fields).

    Hint:
        Use `store` method to save modified record.

    Examples:
        Add new record to the database:
            db = Dbf(filename)
            rec = db.newRecord()
            rec["FIELD1"] = value1
            rec["FIELD2"] = value2
            rec.store()
        Or the same, but modify existed
        (second in this case) record:
            db = Dbf(filename)
            rec = db[2]
            rec["FIELD1"] = value1
            rec["FIELD2"] = value2
            rec.store()

    """

    __slots__ = "dbf", "index", "deleted", "fieldData"

    ## creation and initialization

    def __init__(self, dbf, index=None, deleted=False, data=None):
        """Instance initialiation.

        Arguments:
            dbf:
                A `Dbf.Dbf` instance this record belonogs to.
            index:
                An integer record index or None. If this value is
                None, record will be appended to the DBF.
            deleted:
                Boolean flag indicating whether this record
                is a deleted record.
            data:
                A sequence or None. This is a data of the fields.
                If this argument is None, default values will be used.

        """
        self.dbf = dbf
        # XXX: I'm not sure ``index`` is necessary
        self.index = index
        self.deleted = deleted
        if data is None:
            self.fieldData = [_fd.defaultValue for _fd in dbf.header.fields]
        else:
            self.fieldData = list(data)

    # XXX: validate self.index before calculating position?
    position = property(lambda self: self.dbf.header.headerLength + \
        self.index * self.dbf.header.recordLength)

    def rawFromStream(cls, dbf, index):
        """Return raw record contents read from the stream.

        Arguments:
            dbf:
                A `Dbf.Dbf` instance containing the record.
            index:
                Index of the record in the records' container.
                This argument can't be None in this call.

        Return value is a string containing record data in DBF format.

        """
        # XXX: may be write smth assuming, that current stream
        # position is the required one? it could save some
        # time required to calculate where to seek in the file
        dbf.stream.seek(dbf.header.headerLength +
            index * dbf.header.recordLength)
        return dbf.stream.read(dbf.header.recordLength)
    rawFromStream = classmethod(rawFromStream)

    def fromStream(cls, dbf, index):
        """Return a record read from the stream.

        Arguments:
            dbf:
                A `Dbf.Dbf` instance new record should belong to.
            index:
                Index of the record in the records' container.
                This argument can't be None in this call.

        Return value is an instance of the current class.

        """
        return cls.fromString(dbf, cls.rawFromStream(dbf, index), index)
    fromStream = classmethod(fromStream)

    def fromString(cls, dbf, string, index=None):
        """Return record read from the string object.

        Arguments:
            dbf:
                A `Dbf.Dbf` instance new record should belong to.
            string:
                A string new record should be created from.
            index:
                Index of the record in the container. If this
                argument is None, record will be appended.

        Return value is an instance of the current class.

        """
        return cls(dbf, index, string[0]=="*",
            [_fd.decodeFromRecord(string) for _fd in dbf.header.fields])
    fromString = classmethod(fromString)

    ## object representation

    def __repr__(self):
        _template = "%%%ds: %%s (%%s)" % max([len(_fld)
            for _fld in self.dbf.fieldNames])
        _rv = []
        for _fld in self.dbf.fieldNames:
            _val = self[_fld]
            if _val is utils.INVALID_VALUE:
                _rv.append(_template %
                    (_fld, "None", "value cannot be decoded"))
            else:
                _rv.append(_template % (_fld, _val, type(_val)))
        return "\n".join(_rv)

    ## protected methods

    def _write(self):
        """Write data to the dbf stream.

        Note:
            This isn't a public method, it's better to
            use 'store' instead publically.
            Be design ``_write`` method should be called
            only from the `Dbf` instance.


        """
        self._validateIndex(False)
        self.dbf.stream.seek(self.position)
        self.dbf.stream.write(bytes(self.toString(),
            sys.getfilesystemencoding()))
        # FIXME: may be move this write somewhere else?
        # why we should check this condition for each record?
        if self.index == len(self.dbf):
            # this is the last record,
            # we should write SUB (ASCII 26)
            self.dbf.stream.write(b"\x1A")

    ## utility methods

    def _validateIndex(self, allowUndefined=True, checkRange=False):
        """Valid ``self.index`` value.

        If ``allowUndefined`` argument is True functions does nothing
        in case of ``self.index`` pointing to None object.

        """
        if self.index is None:
            if not allowUndefined:
                raise ValueError("Index is undefined")
        elif self.index < 0:
            raise ValueError("Index can't be negative (%s)" % self.index)
        elif checkRange and self.index <= self.dbf.header.recordCount:
            raise ValueError("There are only %d records in the DBF" %
                self.dbf.header.recordCount)

    ## interface methods

    def store(self):
        """Store current record in the DBF.

        If ``self.index`` is None, this record will be appended to the
        records of the DBF this records belongs to; or replaced otherwise.

        """
        self._validateIndex()
        if self.index is None:
            self.index = len(self.dbf)
            self.dbf.append(self)
        else:
            self.dbf[self.index] = self

    def delete(self):
        """Mark method as deleted."""
        self.deleted = True

    def toString(self):
        """Return string packed record values."""
#        for (_def, _dat) in zip(self.dbf.header.fields, self.fieldData):
#

        return "".join([" *"[self.deleted]] + [
           _def.encodeValue(_dat)
            for (_def, _dat) in zip(self.dbf.header.fields, self.fieldData)
        ])

    def asList(self):
        """Return a flat list of fields.

        Note:
            Change of the list's values won't change
            real values stored in this object.

        """
        return self.fieldData[:]

    def asDict(self):
        """Return a dictionary of fields.

        Note:
            Change of the dicts's values won't change
            real values stored in this object.

        """
        return dict([_i for _i in zip(self.dbf.fieldNames, self.fieldData)])

    def __getitem__(self, key):
        """Return value by field name or field index."""
        if isinstance(key, int):
            # integer index of the field
            return self.fieldData[key]
        # assuming string field name
        return self.fieldData[self.dbf.indexOfFieldName(key)]

    def __setitem__(self, key, value):
        """Set field value by integer index of the field or string name."""
        if isinstance(key, int):
            # integer index of the field
            return self.fieldData[key]
        # assuming string field name
        self.fieldData[self.dbf.indexOfFieldName(key)] = value

# vim: et sts=4 sw=4 :