1 "table definitions"
2 import os
3 import sys
4 import csv
5 import codecs
6 import locale
7 import unicodedata
8 import weakref
9 from array import array
10 from bisect import bisect_left, bisect_right
11 from decimal import Decimal
12 from shutil import copyfileobj
13 import dbf
14 from dbf import _io as io
15 from dbf.dates import Date, DateTime, Time
16 from dbf.exceptions import Bof, Eof, DbfError, DataOverflow, FieldMissing, NonUnicode, DoNotIndex
17
18 input_decoding = locale.getdefaultlocale()[1]
19 default_codepage = 'cp1252'
20 return_ascii = True
21 temp_dir = os.environ.get("DBF_TEMP") or os.environ.get("TEMP") or ""
22
23 version_map = {
24 '\x02' : 'FoxBASE',
25 '\x03' : 'dBase III Plus',
26 '\x04' : 'dBase IV',
27 '\x05' : 'dBase V',
28 '\x30' : 'Visual FoxPro',
29 '\x31' : 'Visual FoxPro (auto increment field)',
30 '\x43' : 'dBase IV SQL',
31 '\x7b' : 'dBase IV w/memos',
32 '\x83' : 'dBase III Plus w/memos',
33 '\x8b' : 'dBase IV w/memos',
34 '\x8e' : 'dBase IV w/SQL table',
35 '\xf5' : 'FoxPro w/memos'}
36
37 code_pages = {
38 '\x00' : ('ascii', "plain ol' ascii"),
39 '\x01' : ('cp437', 'U.S. MS-DOS'),
40 '\x02' : ('cp850', 'International MS-DOS'),
41 '\x03' : ('cp1252', 'Windows ANSI'),
42 '\x04' : ('mac_roman', 'Standard Macintosh'),
43 '\x08' : ('cp865', 'Danish OEM'),
44 '\x09' : ('cp437', 'Dutch OEM'),
45 '\x0A' : ('cp850', 'Dutch OEM (secondary)'),
46 '\x0B' : ('cp437', 'Finnish OEM'),
47 '\x0D' : ('cp437', 'French OEM'),
48 '\x0E' : ('cp850', 'French OEM (secondary)'),
49 '\x0F' : ('cp437', 'German OEM'),
50 '\x10' : ('cp850', 'German OEM (secondary)'),
51 '\x11' : ('cp437', 'Italian OEM'),
52 '\x12' : ('cp850', 'Italian OEM (secondary)'),
53 '\x13' : ('cp932', 'Japanese Shift-JIS'),
54 '\x14' : ('cp850', 'Spanish OEM (secondary)'),
55 '\x15' : ('cp437', 'Swedish OEM'),
56 '\x16' : ('cp850', 'Swedish OEM (secondary)'),
57 '\x17' : ('cp865', 'Norwegian OEM'),
58 '\x18' : ('cp437', 'Spanish OEM'),
59 '\x19' : ('cp437', 'English OEM (Britain)'),
60 '\x1A' : ('cp850', 'English OEM (Britain) (secondary)'),
61 '\x1B' : ('cp437', 'English OEM (U.S.)'),
62 '\x1C' : ('cp863', 'French OEM (Canada)'),
63 '\x1D' : ('cp850', 'French OEM (secondary)'),
64 '\x1F' : ('cp852', 'Czech OEM'),
65 '\x22' : ('cp852', 'Hungarian OEM'),
66 '\x23' : ('cp852', 'Polish OEM'),
67 '\x24' : ('cp860', 'Portugese OEM'),
68 '\x25' : ('cp850', 'Potugese OEM (secondary)'),
69 '\x26' : ('cp866', 'Russian OEM'),
70 '\x37' : ('cp850', 'English OEM (U.S.) (secondary)'),
71 '\x40' : ('cp852', 'Romanian OEM'),
72 '\x4D' : ('cp936', 'Chinese GBK (PRC)'),
73 '\x4E' : ('cp949', 'Korean (ANSI/OEM)'),
74 '\x4F' : ('cp950', 'Chinese Big 5 (Taiwan)'),
75 '\x50' : ('cp874', 'Thai (ANSI/OEM)'),
76 '\x57' : ('cp1252', 'ANSI'),
77 '\x58' : ('cp1252', 'Western European ANSI'),
78 '\x59' : ('cp1252', 'Spanish ANSI'),
79 '\x64' : ('cp852', 'Eastern European MS-DOS'),
80 '\x65' : ('cp866', 'Russian MS-DOS'),
81 '\x66' : ('cp865', 'Nordic MS-DOS'),
82 '\x67' : ('cp861', 'Icelandic MS-DOS'),
83 '\x68' : (None, 'Kamenicky (Czech) MS-DOS'),
84 '\x69' : (None, 'Mazovia (Polish) MS-DOS'),
85 '\x6a' : ('cp737', 'Greek MS-DOS (437G)'),
86 '\x6b' : ('cp857', 'Turkish MS-DOS'),
87 '\x78' : ('cp950', 'Traditional Chinese (Hong Kong SAR, Taiwan) Windows'),
88 '\x79' : ('cp949', 'Korean Windows'),
89 '\x7a' : ('cp936', 'Chinese Simplified (PRC, Singapore) Windows'),
90 '\x7b' : ('cp932', 'Japanese Windows'),
91 '\x7c' : ('cp874', 'Thai Windows'),
92 '\x7d' : ('cp1255', 'Hebrew Windows'),
93 '\x7e' : ('cp1256', 'Arabic Windows'),
94 '\xc8' : ('cp1250', 'Eastern European Windows'),
95 '\xc9' : ('cp1251', 'Russian Windows'),
96 '\xca' : ('cp1254', 'Turkish Windows'),
97 '\xcb' : ('cp1253', 'Greek Windows'),
98 '\x96' : ('mac_cyrillic', 'Russian Macintosh'),
99 '\x97' : ('mac_latin2', 'Macintosh EE'),
100 '\x98' : ('mac_greek', 'Greek Macintosh') }
101
102 if sys.version_info[:2] < (2, 6):
105 "Emulate PyProperty_Type() in Objects/descrobject.c"
106
107 - def __init__(self, fget=None, fset=None, fdel=None, doc=None):
108 self.fget = fget
109 self.fset = fset
110 self.fdel = fdel
111 self.__doc__ = doc or fget.__doc__
113 self.fget = func
114 if not self.__doc__:
115 self.__doc__ = fget.__doc__
116 - def __get__(self, obj, objtype=None):
117 if obj is None:
118 return self
119 if self.fget is None:
120 raise AttributeError, "unreadable attribute"
121 return self.fget(obj)
123 if self.fset is None:
124 raise AttributeError, "can't set attribute"
125 self.fset(obj, value)
127 if self.fdel is None:
128 raise AttributeError, "can't delete attribute"
129 self.fdel(obj)
131 self.fset = func
132 return self
134 self.fdel = func
135 return self
136
138 """Provides routines to extract and save data within the fields of a dbf record."""
139 __slots__ = ['_recnum', '_layout', '_data', '_dirty', '__weakref__']
141 """calls appropriate routine to fetch value stored in field from array
142 @param record_data: the data portion of the record
143 @type record_data: array of characters
144 @param fielddef: description of the field definition
145 @type fielddef: dictionary with keys 'type', 'start', 'length', 'end', 'decimals', and 'flags'
146 @returns: python data stored in field"""
147
148 field_type = fielddef['type']
149 classtype = yo._layout.fieldtypes[field_type]['Class']
150 retrieve = yo._layout.fieldtypes[field_type]['Retrieve']
151 if classtype is not None:
152 datum = retrieve(record_data, fielddef, yo._layout.memo, classtype)
153 else:
154 datum = retrieve(record_data, fielddef, yo._layout.memo)
155 if field_type in yo._layout.character_fields:
156 datum = yo._layout.decoder(datum)[0]
157 if yo._layout.return_ascii:
158 try:
159 datum = yo._layout.output_encoder(datum)[0]
160 except UnicodeEncodeError:
161 datum = unicodedata.normalize('NFD', datum).encode('ascii','ignore')
162 return datum
164 "calls appropriate routine to convert value to ascii bytes, and save it in record"
165 field_type = fielddef['type']
166 update = yo._layout.fieldtypes[field_type]['Update']
167 if field_type in yo._layout.character_fields:
168 if not isinstance(value, unicode):
169 if yo._layout.input_decoder is None:
170 raise NonUnicode("String not in unicode format, no default encoding specified")
171 value = yo._layout.input_decoder(value)[0]
172 value = yo._layout.encoder(value)[0]
173 bytes = array('c', update(value, fielddef, yo._layout.memo))
174 size = fielddef['length']
175 if len(bytes) > size:
176 raise DataOverflow("tried to store %d bytes in %d byte field" % (len(bytes), size))
177 blank = array('c', ' ' * size)
178 start = fielddef['start']
179 end = start + size
180 blank[:len(bytes)] = bytes[:]
181 yo._data[start:end] = blank[:]
182 yo._dirty = True
197 results = []
198 if not specs:
199 specs = yo._layout.index
200 specs = _normalize_tuples(tuples=specs, length=2, filler=[_nop])
201 for field, func in specs:
202 results.append(func(yo[field]))
203 return tuple(results)
204
210 if name[0:2] == '__' and name[-2:] == '__':
211 raise AttributeError, 'Method %s is not implemented.' % name
212 elif name == 'record_number':
213 return yo._recnum
214 elif name == 'delete_flag':
215 return yo._data[0] != ' '
216 elif not name in yo._layout.fields:
217 raise FieldMissing(name)
218 try:
219 fielddef = yo._layout[name]
220 value = yo._retrieveFieldValue(yo._data[fielddef['start']:fielddef['end']], fielddef)
221 return value
222 except DbfError, error:
223 error.message = "field --%s-- is %s -> %s" % (name, yo._layout.fieldtypes[fielddef['type']]['Type'], error.message)
224 raise
241 - def __new__(cls, recnum, layout, kamikaze='', _fromdisk=False):
280 if type(name) == str:
281 yo.__setattr__(name, value)
282 elif type(name) in (int, long):
283 yo.__setattr__(yo._layout.fields[name], value)
284 elif type(name) == slice:
285 sequence = []
286 for field in yo._layout.fields[name]:
287 sequence.append(field)
288 if len(sequence) != len(value):
289 raise DbfError("length of slices not equal")
290 for field, val in zip(sequence, value):
291 yo[field] = val
292 else:
293 raise TypeError("%s is not a field name" % name)
295 result = []
296 for seq, field in enumerate(yo.field_names):
297 result.append("%3d - %-10s: %s" % (seq, field, yo[field]))
298 return '\n'.join(result)
300 return yo._data.tostring()
302 "creates a blank record data chunk"
303 layout = yo._layout
304 ondisk = layout.ondisk
305 layout.ondisk = False
306 yo._data = array('c', ' ' * layout.header.record_length)
307 layout.memofields = []
308 for field in layout.fields:
309 yo._updateFieldValue(layout[field], layout.fieldtypes[layout[field]['type']]['Blank']())
310 if layout[field]['type'] in layout.memotypes:
311 layout.memofields.append(field)
312 layout.blankrecord = yo._data[:]
313 layout.ondisk = ondisk
315 "marks record as deleted"
316 yo._data[0] = '*'
317 yo._dirty = True
318 return yo
319 @property
324 "saves a dictionary into a record's fields\nkeys with no matching field will raise a FieldMissing exception unless drop_missing = True"
325 old_data = yo._data[:]
326 try:
327 for key in dictionary:
328 if not key in yo.field_names:
329 if drop:
330 continue
331 raise FieldMissing(key)
332 yo.__setattr__(key, dictionary[key])
333 except:
334 yo._data[:] = old_data
335 raise
336 return yo
337 @property
339 "marked for deletion?"
340 return yo._data[0] == '*'
349 @property
351 "physical record number"
352 return yo._recnum
353 @property
355 table = yo._layout.table()
356 if table is None:
357 raise DbfError("table is no longer available")
358 return table
360 for dbfindex in yo._layout.table()._indexen:
361 dbfindex(yo)
363 "blanks record"
364 if keep_fields is None:
365 keep_fields = []
366 keep = {}
367 for field in keep_fields:
368 keep[field] = yo[field]
369 if yo._layout.blankrecord == None:
370 yo._createBlankRecord()
371 yo._data[:] = yo._layout.blankrecord[:]
372 for field in keep_fields:
373 yo[field] = keep[field]
374 yo._dirty = True
375 return yo
377 "returns a dictionary of fieldnames and values which can be used with gather_fields(). if blank is True, values are empty."
378 keys = yo._layout.fields
379 if blank:
380 values = [yo._layout.fieldtypes[yo._layout[key]['type']]['Blank']() for key in keys]
381 else:
382 values = [yo[field] for field in keys]
383 return dict(zip(keys, values))
385 "marks record as active"
386 yo._data[0] = ' '
387 yo._dirty = True
388 return yo
398 """Provides access to memo fields as dictionaries
399 must override _init, _get_memo, and _put_memo to
400 store memo contents to disk"""
402 "initialize disk file usage"
404 "retrieve memo contents from disk"
406 "store memo contents to disk"
408 ""
409 yo.meta = meta
410 yo.memory = {}
411 yo.nextmemo = 1
412 yo._init()
413 yo.meta.newmemofile = False
415 "gets the memo in block"
416 if yo.meta.ignorememos or not block:
417 return ''
418 if yo.meta.ondisk:
419 return yo._get_memo(block)
420 else:
421 return yo.memory[block]
423 "stores data in memo file, returns block number"
424 if yo.meta.ignorememos or data == '':
425 return 0
426 if yo.meta.inmemory:
427 thismemo = yo.nextmemo
428 yo.nextmemo += 1
429 yo.memory[thismemo] = data
430 else:
431 thismemo = yo._put_memo(data)
432 return thismemo
435 "dBase III specific"
436 yo.meta.memo_size= 512
437 yo.record_header_length = 2
438 if yo.meta.ondisk and not yo.meta.ignorememos:
439 if yo.meta.newmemofile:
440 yo.meta.mfd = open(yo.meta.memoname, 'w+b')
441 yo.meta.mfd.write(io.packLongInt(1) + '\x00' * 508)
442 else:
443 try:
444 yo.meta.mfd = open(yo.meta.memoname, 'r+b')
445 yo.meta.mfd.seek(0)
446 yo.nextmemo = io.unpackLongInt(yo.meta.mfd.read(4))
447 except:
448 raise DbfError("memo file appears to be corrupt")
450 block = int(block)
451 yo.meta.mfd.seek(block * yo.meta.memo_size)
452 eom = -1
453 data = ''
454 while eom == -1:
455 newdata = yo.meta.mfd.read(yo.meta.memo_size)
456 if not newdata:
457 return data
458 data += newdata
459 eom = data.find('\x1a\x1a')
460 return data[:eom].rstrip()
462 data = data.rstrip()
463 length = len(data) + yo.record_header_length
464 blocks = length // yo.meta.memo_size
465 if length % yo.meta.memo_size:
466 blocks += 1
467 thismemo = yo.nextmemo
468 yo.nextmemo = thismemo + blocks
469 yo.meta.mfd.seek(0)
470 yo.meta.mfd.write(io.packLongInt(yo.nextmemo))
471 yo.meta.mfd.seek(thismemo * yo.meta.memo_size)
472 yo.meta.mfd.write(data)
473 yo.meta.mfd.write('\x1a\x1a')
474 double_check = yo._get_memo(thismemo)
475 if len(double_check) != len(data):
476 uhoh = open('dbf_memo_dump.err','wb')
477 uhoh.write('thismemo: %d' % thismemo)
478 uhoh.write('nextmemo: %d' % yo.nextmemo)
479 uhoh.write('saved: %d bytes' % len(data))
480 uhoh.write(data)
481 uhoh.write('retrieved: %d bytes' % len(double_check))
482 uhoh.write(double_check)
483 uhoh.close()
484 raise DbfError("unknown error: memo not saved")
485 return thismemo
488 "Visual Foxpro 6 specific"
489 if yo.meta.ondisk and not yo.meta.ignorememos:
490 yo.record_header_length = 8
491 if yo.meta.newmemofile:
492 if yo.meta.memo_size == 0:
493 yo.meta.memo_size = 1
494 elif 1 < yo.meta.memo_size < 33:
495 yo.meta.memo_size *= 512
496 yo.meta.mfd = open(yo.meta.memoname, 'w+b')
497 nextmemo = 512 // yo.meta.memo_size
498 if nextmemo * yo.meta.memo_size < 512:
499 nextmemo += 1
500 yo.nextmemo = nextmemo
501 yo.meta.mfd.write(io.packLongInt(nextmemo, bigendian=True) + '\x00\x00' + \
502 io.packShortInt(yo.meta.memo_size, bigendian=True) + '\x00' * 504)
503 else:
504 try:
505 yo.meta.mfd = open(yo.meta.memoname, 'r+b')
506 yo.meta.mfd.seek(0)
507 header = yo.meta.mfd.read(512)
508 yo.nextmemo = io.unpackLongInt(header[:4], bigendian=True)
509 yo.meta.memo_size = io.unpackShortInt(header[6:8], bigendian=True)
510 except:
511 raise DbfError("memo file appears to be corrupt")
513 yo.meta.mfd.seek(block * yo.meta.memo_size)
514 header = yo.meta.mfd.read(8)
515 length = io.unpackLongInt(header[4:], bigendian=True)
516 return yo.meta.mfd.read(length)
518 data = data.rstrip()
519 yo.meta.mfd.seek(0)
520 thismemo = io.unpackLongInt(yo.meta.mfd.read(4), bigendian=True)
521 yo.meta.mfd.seek(0)
522 length = len(data) + yo.record_header_length
523 blocks = length // yo.meta.memo_size
524 if length % yo.meta.memo_size:
525 blocks += 1
526 yo.meta.mfd.write(io.packLongInt(thismemo+blocks, bigendian=True))
527 yo.meta.mfd.seek(thismemo*yo.meta.memo_size)
528 yo.meta.mfd.write('\x00\x00\x00\x01' + io.packLongInt(len(data), bigendian=True) + data)
529 return thismemo
530
532 """Provides a framework for dbf style tables."""
533 _version = 'basic memory table'
534 _versionabbv = 'dbf'
535 _fieldtypes = {
536 'D' : { 'Type':'Date', 'Init':io.addDate, 'Blank':Date.today, 'Retrieve':io.retrieveDate, 'Update':io.updateDate, 'Class':None},
537 'L' : { 'Type':'Logical', 'Init':io.addLogical, 'Blank':bool, 'Retrieve':io.retrieveLogical, 'Update':io.updateLogical, 'Class':None},
538 'M' : { 'Type':'Memo', 'Init':io.addMemo, 'Blank':str, 'Retrieve':io.retrieveMemo, 'Update':io.updateMemo, 'Class':None} }
539 _memoext = ''
540 _memotypes = tuple('M', )
541 _memoClass = _DbfMemo
542 _yesMemoMask = ''
543 _noMemoMask = ''
544 _fixed_fields = ('M','D','L')
545 _variable_fields = tuple()
546 _character_fields = tuple('M', )
547 _decimal_fields = tuple()
548 _numeric_fields = tuple()
549 _currency_fields = tuple()
550 _dbfTableHeader = array('c', '\x00' * 32)
551 _dbfTableHeader[0] = '\x00'
552 _dbfTableHeader[8:10] = array('c', io.packShortInt(33))
553 _dbfTableHeader[10] = '\x01'
554 _dbfTableHeader[29] = '\x00'
555 _dbfTableHeader = _dbfTableHeader.tostring()
556 _dbfTableHeaderExtra = ''
557 _supported_tables = []
558 _read_only = False
559 _meta_only = False
560 _use_deleted = True
561 backup = False
563 "implements the weakref structure for DbfLists"
567 yo._lists = set([s for s in yo._lists if s() is not None])
568 return (s() for s in yo._lists if s() is not None)
570 yo._lists = set([s for s in yo._lists if s() is not None])
571 return len(yo._lists)
572 - def add(yo, new_list):
573 yo._lists.add(weakref.ref(new_list))
574 yo._lists = set([s for s in yo._lists if s() is not None])
576 "implements the weakref structure for seperate indexes"
580 yo._indexen = set([s for s in yo._indexen if s() is not None])
581 return (s() for s in yo._indexen if s() is not None)
583 yo._indexen = set([s for s in yo._indexen if s() is not None])
584 return len(yo._indexen)
585 - def add(yo, new_list):
586 yo._indexen.add(weakref.ref(new_list))
587 yo._indexen = set([s for s in yo._indexen if s() is not None])
602 if len(data) != 32:
603 raise DbfError('table header should be 32 bytes, but is %d bytes' % len(data))
604 yo._data = array('c', data + '\x0d')
606 "get/set code page of table"
607 if cp is None:
608 return yo._data[29]
609 else:
610 cp, sd, ld = _codepage_lookup(cp)
611 yo._data[29] = cp
612 return cp
613 @property
619 @data.setter
621 if len(bytes) < 32:
622 raise DbfError("length for data of %d is less than 32" % len(bytes))
623 yo._data[:] = array('c', bytes)
624 @property
626 "extra dbf info (located after headers, before data records)"
627 fieldblock = yo._data[32:]
628 for i in range(len(fieldblock)//32+1):
629 cr = i * 32
630 if fieldblock[cr] == '\x0d':
631 break
632 else:
633 raise DbfError("corrupt field structure")
634 cr += 33
635 return yo._data[cr:].tostring()
636 @extra.setter
638 fieldblock = yo._data[32:]
639 for i in range(len(fieldblock)//32+1):
640 cr = i * 32
641 if fieldblock[cr] == '\x0d':
642 break
643 else:
644 raise DbfError("corrupt field structure")
645 cr += 33
646 yo._data[cr:] = array('c', data)
647 yo._data[8:10] = array('c', io.packShortInt(len(yo._data)))
648 @property
650 "number of fields (read-only)"
651 fieldblock = yo._data[32:]
652 for i in range(len(fieldblock)//32+1):
653 cr = i * 32
654 if fieldblock[cr] == '\x0d':
655 break
656 else:
657 raise DbfError("corrupt field structure")
658 return len(fieldblock[:cr]) // 32
659 @property
661 "field block structure"
662 fieldblock = yo._data[32:]
663 for i in range(len(fieldblock)//32+1):
664 cr = i * 32
665 if fieldblock[cr] == '\x0d':
666 break
667 else:
668 raise DbfError("corrupt field structure")
669 return fieldblock[:cr].tostring()
670 @fields.setter
672 fieldblock = yo._data[32:]
673 for i in range(len(fieldblock)//32+1):
674 cr = i * 32
675 if fieldblock[cr] == '\x0d':
676 break
677 else:
678 raise DbfError("corrupt field structure")
679 cr += 32
680 fieldlen = len(block)
681 if fieldlen % 32 != 0:
682 raise DbfError("fields structure corrupt: %d is not a multiple of 32" % fieldlen)
683 yo._data[32:cr] = array('c', block)
684 yo._data[8:10] = array('c', io.packShortInt(len(yo._data)))
685 fieldlen = fieldlen // 32
686 recordlen = 1
687 for i in range(fieldlen):
688 recordlen += ord(block[i*32+16])
689 yo._data[10:12] = array('c', io.packShortInt(recordlen))
690 @property
692 "number of records (maximum 16,777,215)"
693 return io.unpackLongInt(yo._data[4:8].tostring())
694 @record_count.setter
697 @property
699 "length of a record (read_only) (max of 65,535)"
700 return io.unpackShortInt(yo._data[10:12].tostring())
701 @property
703 "starting position of first record in file (must be within first 64K)"
704 return io.unpackShortInt(yo._data[8:10].tostring())
705 @start.setter
708 @property
710 "date of last table modification (read-only)"
711 return io.unpackDate(yo._data[1:4].tostring())
712 @property
714 "dbf version"
715 return yo._data[0]
716 @version.setter
720 "implements the weakref table for records"
722 yo._meta = meta
723 yo._weakref_list = [weakref.ref(lambda x: None)] * count
725 maybe = yo._weakref_list[index]()
726 if maybe is None:
727 if index < 0:
728 index += yo._meta.header.record_count
729 size = yo._meta.header.record_length
730 location = index * size + yo._meta.header.start
731 yo._meta.dfd.seek(location)
732 if yo._meta.dfd.tell() != location:
733 raise ValueError("unable to seek to offset %d in file" % location)
734 bytes = yo._meta.dfd.read(size)
735 if not bytes:
736 raise ValueError("unable to read record data from %s at location %d" % (yo._meta.filename, location))
737 maybe = _DbfRecord(recnum=index, layout=yo._meta, kamikaze=bytes, _fromdisk=True)
738 yo._weakref_list[index] = weakref.ref(maybe)
739 return maybe
741 yo._weakref_list.append(weakref.ref(record))
743 yo._weakref_list[:] = []
745 return yo._weakref_list.pop()
747 "returns records using current index"
749 yo._table = table
750 yo._index = -1
751 yo._more_records = True
755 while yo._more_records:
756 yo._index += 1
757 if yo._index >= len(yo._table):
758 yo._more_records = False
759 continue
760 record = yo._table[yo._index]
761 if not yo._table.use_deleted and record.has_been_deleted:
762 continue
763 return record
764 else:
765 raise StopIteration
767 "constructs fieldblock for disk table"
768 fieldblock = array('c', '')
769 memo = False
770 yo._meta.header.version = chr(ord(yo._meta.header.version) & ord(yo._noMemoMask))
771 for field in yo._meta.fields:
772 if yo._meta.fields.count(field) > 1:
773 raise DbfError("corrupted field structure (noticed in _buildHeaderFields)")
774 fielddef = array('c', '\x00' * 32)
775 fielddef[:11] = array('c', io.packStr(field))
776 fielddef[11] = yo._meta[field]['type']
777 fielddef[12:16] = array('c', io.packLongInt(yo._meta[field]['start']))
778 fielddef[16] = chr(yo._meta[field]['length'])
779 fielddef[17] = chr(yo._meta[field]['decimals'])
780 fielddef[18] = chr(yo._meta[field]['flags'])
781 fieldblock.extend(fielddef)
782 if yo._meta[field]['type'] in yo._meta.memotypes:
783 memo = True
784 yo._meta.header.fields = fieldblock.tostring()
785 if memo:
786 yo._meta.header.version = chr(ord(yo._meta.header.version) | ord(yo._yesMemoMask))
787 if yo._meta.memo is None:
788 yo._meta.memo = yo._memoClass(yo._meta)
790 "dBase III specific"
791 if yo._meta.header.version == '\x83':
792 try:
793 yo._meta.memo = yo._memoClass(yo._meta)
794 except:
795 yo._meta.dfd.close()
796 yo._meta.dfd = None
797 raise
798 if not yo._meta.ignorememos:
799 for field in yo._meta.fields:
800 if yo._meta[field]['type'] in yo._memotypes:
801 if yo._meta.header.version != '\x83':
802 yo._meta.dfd.close()
803 yo._meta.dfd = None
804 raise DbfError("Table structure corrupt: memo fields exist, header declares no memos")
805 elif not os.path.exists(yo._meta.memoname):
806 yo._meta.dfd.close()
807 yo._meta.dfd = None
808 raise DbfError("Table structure corrupt: memo fields exist without memo file")
809 break
811 "builds the FieldList of names, types, and descriptions from the disk file"
812 yo._meta.fields[:] = []
813 offset = 1
814 fieldsdef = yo._meta.header.fields
815 if len(fieldsdef) % 32 != 0:
816 raise DbfError("field definition block corrupt: %d bytes in size" % len(fieldsdef))
817 if len(fieldsdef) // 32 != yo.field_count:
818 raise DbfError("Header shows %d fields, but field definition block has %d fields" % (yo.field_count, len(fieldsdef)//32))
819 for i in range(yo.field_count):
820 fieldblock = fieldsdef[i*32:(i+1)*32]
821 name = io.unpackStr(fieldblock[:11])
822 type = fieldblock[11]
823 if not type in yo._meta.fieldtypes:
824 raise DbfError("Unknown field type: %s" % type)
825 start = offset
826 length = ord(fieldblock[16])
827 offset += length
828 end = start + length
829 decimals = ord(fieldblock[17])
830 flags = ord(fieldblock[18])
831 if name in yo._meta.fields:
832 raise DbfError('Duplicate field name found: %s' % name)
833 yo._meta.fields.append(name)
834 yo._meta[name] = {'type':type,'start':start,'length':length,'end':end,'decimals':decimals,'flags':flags}
836 "Returns field information Name Type(Length[,Decimals])"
837 name = yo._meta.fields[i]
838 type = yo._meta[name]['type']
839 length = yo._meta[name]['length']
840 decimals = yo._meta[name]['decimals']
841 if type in yo._decimal_fields:
842 description = "%s %s(%d,%d)" % (name, type, length, decimals)
843 elif type in yo._fixed_fields:
844 description = "%s %s" % (name, type)
845 else:
846 description = "%s %s(%d)" % (name, type, length)
847 return description
849 "loads the records from disk to memory"
850 if yo._meta_only:
851 raise DbfError("%s has been closed, records are unavailable" % yo.filename)
852 dfd = yo._meta.dfd
853 header = yo._meta.header
854 dfd.seek(header.start)
855 allrecords = dfd.read()
856 dfd.seek(0)
857 length = header.record_length
858 for i in range(header.record_count):
859 record_data = allrecords[length*i:length*i+length]
860 yo._table.append(_DbfRecord(i, yo._meta, allrecords[length*i:length*i+length], _fromdisk=True))
861 dfd.seek(0)
863 if specs is None:
864 specs = yo.field_names
865 elif isinstance(specs, str):
866 specs = specs.split(sep)
867 else:
868 specs = list(specs)
869 specs = [s.strip() for s in specs]
870 return specs
872 "synchronizes the disk file with current data"
873 if yo._meta.inmemory:
874 return
875 fd = yo._meta.dfd
876 fd.seek(0)
877 fd.write(yo._meta.header.data)
878 if not headeronly:
879 for record in yo._table:
880 record._update_disk()
881 fd.flush()
882 fd.truncate(yo._meta.header.start + yo._meta.header.record_count * yo._meta.header.record_length)
883 if 'db3' in yo._versionabbv:
884 fd.seek(0, os.SEEK_END)
885 fd.write('\x1a')
886 fd.flush()
887 fd.truncate(yo._meta.header.start + yo._meta.header.record_count * yo._meta.header.record_length + 1)
888
896 if name in ('_table'):
897 if yo._meta.ondisk:
898 yo._table = yo._Table(len(yo), yo._meta)
899 else:
900 yo._table = []
901 yo._loadtable()
902 return object.__getattribute__(yo, name)
904 if type(value) == int:
905 if not -yo._meta.header.record_count <= value < yo._meta.header.record_count:
906 raise IndexError("Record %d is not in table." % value)
907 return yo._table[value]
908 elif type(value) == slice:
909 sequence = List(desc='%s --> %s' % (yo.filename, value), field_names=yo.field_names)
910 yo._dbflists.add(sequence)
911 for index in range(len(yo))[value]:
912 record = yo._table[index]
913 if yo.use_deleted is True or not record.has_been_deleted:
914 sequence.append(record)
915 return sequence
916 else:
917 raise TypeError('type <%s> not valid for indexing' % type(value))
918 - def __init__(yo, filename=':memory:', field_specs=None, memo_size=128, ignore_memos=False,
919 read_only=False, keep_memos=False, meta_only=False, codepage=None,
920 numbers='default', strings=str, currency=Decimal):
921 """open/create dbf file
922 filename should include path if needed
923 field_specs can be either a ;-delimited string or a list of strings
924 memo_size is always 512 for db3 memos
925 ignore_memos is useful if the memo file is missing or corrupt
926 read_only will load records into memory, then close the disk file
927 keep_memos will also load any memo fields into memory
928 meta_only will ignore all records, keeping only basic table information
929 codepage will override whatever is set in the table itself"""
930 if filename[0] == filename[-1] == ':':
931 if field_specs is None:
932 raise DbfError("field list must be specified for memory tables")
933 elif type(yo) is DbfTable:
934 raise DbfError("only memory tables supported")
935 yo._dbflists = yo._DbfLists()
936 yo._indexen = yo._Indexen()
937 yo._meta = meta = yo._MetaData()
938 for datatype, classtype in (
939 (yo._character_fields, strings),
940 (yo._numeric_fields, numbers),
941 (yo._currency_fields, currency),
942 ):
943 yo._fieldtypes[datatype] = classtype
944 meta.numbers = numbers
945 meta.strings = strings
946 meta.currency = currency
947 meta.table = weakref.ref(yo)
948 meta.filename = filename
949 meta.fields = []
950 meta.fieldtypes = yo._fieldtypes
951 meta.fixed_fields = yo._fixed_fields
952 meta.variable_fields = yo._variable_fields
953 meta.character_fields = yo._character_fields
954 meta.decimal_fields = yo._decimal_fields
955 meta.numeric_fields = yo._numeric_fields
956 meta.memotypes = yo._memotypes
957 meta.ignorememos = ignore_memos
958 meta.memo_size = memo_size
959 meta.input_decoder = codecs.getdecoder(input_decoding)
960 meta.output_encoder = codecs.getencoder(input_decoding)
961 meta.return_ascii = return_ascii
962 meta.header = header = yo._TableHeader(yo._dbfTableHeader)
963 header.extra = yo._dbfTableHeaderExtra
964 header.data
965 if filename[0] == filename[-1] == ':':
966 yo._table = []
967 meta.ondisk = False
968 meta.inmemory = True
969 meta.memoname = filename
970 else:
971 base, ext = os.path.splitext(filename)
972 if ext == '':
973 meta.filename = base + '.dbf'
974 meta.memoname = base + yo._memoext
975 meta.ondisk = True
976 meta.inmemory = False
977 if field_specs:
978 if meta.ondisk:
979 meta.dfd = open(meta.filename, 'w+b')
980 meta.newmemofile = True
981 yo.add_fields(field_specs)
982 header.codepage(codepage or default_codepage)
983 cp, sd, ld = _codepage_lookup(meta.header.codepage())
984 meta.decoder = codecs.getdecoder(sd)
985 meta.encoder = codecs.getencoder(sd)
986 return
987 try:
988 dfd = meta.dfd = open(meta.filename, 'r+b')
989 except IOError, e:
990 raise DbfError(str(e))
991 dfd.seek(0)
992 meta.header = header = yo._TableHeader(dfd.read(32))
993 if not header.version in yo._supported_tables:
994 dfd.close()
995 dfd = None
996 raise DbfError("Unsupported dbf type: %s [%x]" % (version_map.get(meta.header.version, 'Unknown: %s' % meta.header.version), ord(meta.header.version)))
997 cp, sd, ld = _codepage_lookup(meta.header.codepage())
998 yo._meta.decoder = codecs.getdecoder(sd)
999 yo._meta.encoder = codecs.getencoder(sd)
1000 fieldblock = dfd.read(header.start - 32)
1001 for i in range(len(fieldblock)//32+1):
1002 fieldend = i * 32
1003 if fieldblock[fieldend] == '\x0d':
1004 break
1005 else:
1006 raise DbfError("corrupt field structure in header")
1007 if len(fieldblock[:fieldend]) % 32 != 0:
1008 raise DbfError("corrupt field structure in header")
1009 header.fields = fieldblock[:fieldend]
1010 header.extra = fieldblock[fieldend+1:]
1011 yo._initializeFields()
1012 yo._checkMemoIntegrity()
1013 meta.current = -1
1014 if len(yo) > 0:
1015 meta.current = 0
1016 dfd.seek(0)
1017 if meta_only:
1018 yo.close(keep_table=False, keep_memos=False)
1019 elif read_only:
1020 yo.close(keep_table=True, keep_memos=keep_memos)
1021 if codepage is not None:
1022 cp, sd, ld = _codepage_lookup(codepage)
1023 yo._meta.decoder = codecs.getdecoder(sd)
1024 yo._meta.encoder = codecs.getencoder(sd)
1025
1033 if yo._read_only:
1034 return __name__ + ".Table('%s', read_only=True)" % yo._meta.filename
1035 elif yo._meta_only:
1036 return __name__ + ".Table('%s', meta_only=True)" % yo._meta.filename
1037 else:
1038 return __name__ + ".Table('%s')" % yo._meta.filename
1040 if yo._read_only:
1041 status = "read-only"
1042 elif yo._meta_only:
1043 status = "meta-only"
1044 else:
1045 status = "read/write"
1046 str = """
1047 Table: %s
1048 Type: %s
1049 Codepage: %s
1050 Status: %s
1051 Last updated: %s
1052 Record count: %d
1053 Field count: %d
1054 Record length: %d """ % (yo.filename, version_map.get(yo._meta.header.version,
1055 'unknown - ' + hex(ord(yo._meta.header.version))), yo.codepage, status,
1056 yo.last_update, len(yo), yo.field_count, yo.record_length)
1057 str += "\n --Fields--\n"
1058 for i in range(len(yo._meta.fields)):
1059 str += "%11d) %s\n" % (i, yo._fieldLayout(i))
1060 return str
1061 @property
1063 return "%s (%s)" % code_pages[yo._meta.header.codepage()]
1064 @codepage.setter
1065 - def codepage(yo, cp):
1066 cp = code_pages[yo._meta.header.codepage(cp)][0]
1067 yo._meta.decoder = codecs.getdecoder(cp)
1068 yo._meta.encoder = codecs.getencoder(cp)
1069 yo._update_disk(headeronly=True)
1070 @property
1072 "the number of fields in the table"
1073 return yo._meta.header.field_count
1074 @property
1076 "a list of the fields in the table"
1077 return yo._meta.fields[:]
1078 @property
1080 "table's file name, including path (if specified on open)"
1081 return yo._meta.filename
1082 @property
1084 "date of last update"
1085 return yo._meta.header.update
1086 @property
1088 "table's memo name (if path included in filename on open)"
1089 return yo._meta.memoname
1090 @property
1092 "number of bytes in a record"
1093 return yo._meta.header.record_length
1094 @property
1096 "index number of the current record"
1097 return yo._meta.current
1098 @property
1102 @property
1104 "process or ignore deleted records"
1105 return yo._use_deleted
1106 @use_deleted.setter
1109 @property
1111 "returns the dbf type of the table"
1112 return yo._version
1114 """adds field(s) to the table layout; format is Name Type(Length,Decimals)[; Name Type(Length,Decimals)[...]]
1115 backup table is created with _backup appended to name
1116 then modifies current structure"""
1117 all_records = [record for record in yo]
1118 if yo:
1119 yo.create_backup()
1120 yo._meta.blankrecord = None
1121 meta = yo._meta
1122 offset = meta.header.record_length
1123 fields = yo._list_fields(field_specs, sep=';')
1124 for field in fields:
1125 try:
1126 name, format = field.split()
1127 if name[0] == '_' or name[0].isdigit() or not name.replace('_','').isalnum():
1128 raise DbfError("%s invalid: field names must start with a letter, and can only contain letters, digits, and _" % name)
1129 name = name.lower()
1130 if name in meta.fields:
1131 raise DbfError("Field '%s' already exists" % name)
1132 field_type = format[0].upper()
1133 if len(name) > 10:
1134 raise DbfError("Maximum field name length is 10. '%s' is %d characters long." % (name, len(name)))
1135 if not field_type in meta.fieldtypes.keys():
1136 raise DbfError("Unknown field type: %s" % field_type)
1137 length, decimals = yo._meta.fieldtypes[field_type]['Init'](format)
1138 except ValueError:
1139 raise DbfError("invalid field specifier: %s (multiple fields should be separated with ';'" % field)
1140 start = offset
1141 end = offset + length
1142 offset = end
1143 meta.fields.append(name)
1144 meta[name] = {'type':field_type, 'start':start, 'length':length, 'end':end, 'decimals':decimals, 'flags':0}
1145 if meta[name]['type'] in yo._memotypes and meta.memo is None:
1146 meta.memo = yo._memoClass(meta)
1147 for record in yo:
1148 record[name] = meta.fieldtypes[field_type]['Blank']()
1149 yo._buildHeaderFields()
1150 yo._update_disk()
1151 - def append(yo, kamikaze='', drop=False, multiple=1):
1152 "adds <multiple> blank records, and fills fields with dict/tuple values if present"
1153 if not yo.field_count:
1154 raise DbfError("No fields defined, cannot append")
1155 empty_table = len(yo) == 0
1156 dictdata = False
1157 tupledata = False
1158 if not isinstance(kamikaze, _DbfRecord):
1159 if isinstance(kamikaze, dict):
1160 dictdata = kamikaze
1161 kamikaze = ''
1162 elif isinstance(kamikaze, tuple):
1163 tupledata = kamikaze
1164 kamikaze = ''
1165 newrecord = _DbfRecord(recnum=yo._meta.header.record_count, layout=yo._meta, kamikaze=kamikaze)
1166 yo._table.append(newrecord)
1167 yo._meta.header.record_count += 1
1168 try:
1169 if dictdata:
1170 newrecord.gather_fields(dictdata, drop=drop)
1171 elif tupledata:
1172 for index, item in enumerate(tupledata):
1173 newrecord[index] = item
1174 elif kamikaze == str:
1175 for field in yo._meta.memofields:
1176 newrecord[field] = ''
1177 elif kamikaze:
1178 for field in yo._meta.memofields:
1179 newrecord[field] = kamikaze[field]
1180 newrecord.write_record()
1181 except Exception:
1182 yo._table.pop()
1183 yo._meta.header.record_count = yo._meta.header.record_count - 1
1184 yo._update_disk()
1185 raise
1186 multiple -= 1
1187 if multiple:
1188 data = newrecord._data
1189 single = yo._meta.header.record_count
1190 total = single + multiple
1191 while single < total:
1192 multi_record = _DbfRecord(single, yo._meta, kamikaze=data)
1193 yo._table.append(multi_record)
1194 for field in yo._meta.memofields:
1195 multi_record[field] = newrecord[field]
1196 single += 1
1197 multi_record.write_record()
1198 yo._meta.header.record_count = total
1199 yo._meta.current = yo._meta.header.record_count - 1
1200 newrecord = multi_record
1201 yo._update_disk(headeronly=True)
1202 if empty_table:
1203 yo._meta.current = 0
1204 return newrecord
1205 - def bof(yo, _move=False):
1220 - def bottom(yo, get_record=False):
1221 """sets record pointer to bottom of table
1222 if get_record, seeks to and returns last (non-deleted) record
1223 DbfError if table is empty
1224 Bof if all records deleted and use_deleted is False"""
1225 yo._meta.current = yo._meta.header.record_count
1226 if get_record:
1227 try:
1228 return yo.prev()
1229 except Bof:
1230 yo._meta.current = yo._meta.header.record_count
1231 raise Eof()
1232 - def close(yo, keep_table=False, keep_memos=False):
1233 """closes disk files
1234 ensures table data is available if keep_table
1235 ensures memo data is available if keep_memos"""
1236 yo._meta.inmemory = True
1237 if keep_table:
1238 replacement_table = []
1239 for record in yo._table:
1240 replacement_table.append(record)
1241 yo._table = replacement_table
1242 else:
1243 if yo._meta.ondisk:
1244 yo._meta_only = True
1245 if yo._meta.mfd is not None:
1246 if not keep_memos:
1247 yo._meta.ignorememos = True
1248 else:
1249 memo_fields = []
1250 for field in yo.field_names:
1251 if yo.is_memotype(field):
1252 memo_fields.append(field)
1253 for record in yo:
1254 for field in memo_fields:
1255 record[field] = record[field]
1256 yo._meta.mfd.close()
1257 yo._meta.mfd = None
1258 if yo._meta.ondisk:
1259 yo._meta.dfd.close()
1260 yo._meta.dfd = None
1261 if keep_table:
1262 yo._read_only = True
1263 yo._meta.ondisk = False
1265 "creates a backup table -- ignored if memory table"
1266 if yo.filename[0] == yo.filename[-1] == ':':
1267 return
1268 if new_name is None:
1269 upper = yo.filename.isupper()
1270 name, ext = os.path.splitext(os.path.split(yo.filename)[1])
1271 extra = '_BACKUP' if upper else '_backup'
1272 new_name = os.path.join(temp_dir, name + extra + ext)
1273 else:
1274 overwrite = True
1275 if overwrite or not yo.backup:
1276 bkup = open(new_name, 'wb')
1277 try:
1278 yo._meta.dfd.seek(0)
1279 copyfileobj(yo._meta.dfd, bkup)
1280 yo.backup = new_name
1281 finally:
1282 bkup.close()
1286 "returns current logical record, or its index"
1287 if yo._meta.current < 0:
1288 raise Bof()
1289 elif yo._meta.current >= yo._meta.header.record_count:
1290 raise Eof()
1291 if index:
1292 return yo._meta.current
1293 return yo._table[yo._meta.current]
1295 """removes field(s) from the table
1296 creates backup files with _backup appended to the file name,
1297 then modifies current structure"""
1298 doomed = yo._list_fields(doomed)
1299 for victim in doomed:
1300 if victim not in yo._meta.fields:
1301 raise DbfError("field %s not in table -- delete aborted" % victim)
1302 all_records = [record for record in yo]
1303 yo.create_backup()
1304 for victim in doomed:
1305 yo._meta.fields.pop(yo._meta.fields.index(victim))
1306 start = yo._meta[victim]['start']
1307 end = yo._meta[victim]['end']
1308 for record in yo:
1309 record._data = record._data[:start] + record._data[end:]
1310 for field in yo._meta.fields:
1311 if yo._meta[field]['start'] == end:
1312 end = yo._meta[field]['end']
1313 yo._meta[field]['start'] = start
1314 yo._meta[field]['end'] = start + yo._meta[field]['length']
1315 start = yo._meta[field]['end']
1316 yo._buildHeaderFields()
1317 yo._update_disk()
1318 - def eof(yo, _move=False):
1333 - def export(yo, records=None, filename=None, field_specs=None, format='csv', header=True):
1334 """writes the table using CSV or tab-delimited format, using the filename
1335 given if specified, otherwise the table name"""
1336 if filename is not None:
1337 path, filename = os.path.split(filename)
1338 else:
1339 path, filename = os.path.split(yo.filename)
1340 filename = os.path.join(path, filename)
1341 field_specs = yo._list_fields(field_specs)
1342 if records is None:
1343 records = yo
1344 format = format.lower()
1345 if format not in ('csv', 'tab', 'fixed'):
1346 raise DbfError("export format: csv, tab, or fixed -- not %s" % format)
1347 if format == 'fixed':
1348 format = 'txt'
1349 base, ext = os.path.splitext(filename)
1350 if ext.lower() in ('', '.dbf'):
1351 filename = base + "." + format[:3]
1352 fd = open(filename, 'w')
1353 try:
1354 if format == 'csv':
1355 csvfile = csv.writer(fd, dialect='dbf')
1356 if header:
1357 csvfile.writerow(field_specs)
1358 for record in records:
1359 fields = []
1360 for fieldname in field_specs:
1361 fields.append(record[fieldname])
1362 csvfile.writerow(fields)
1363 elif format == 'tab':
1364 if header:
1365 fd.write('\t'.join(field_specs) + '\n')
1366 for record in records:
1367 fields = []
1368 for fieldname in field_specs:
1369 fields.append(str(record[fieldname]))
1370 fd.write('\t'.join(fields) + '\n')
1371 else:
1372 header = open("%s_layout.txt" % os.path.splitext(filename)[0], 'w')
1373 header.write("%-15s Size\n" % "Field Name")
1374 header.write("%-15s ----\n" % ("-" * 15))
1375 sizes = []
1376 for field in field_specs:
1377 size = yo.size(field)[0]
1378 sizes.append(size)
1379 header.write("%-15s %3d\n" % (field, size))
1380 header.write('\nTotal Records in file: %d\n' % len(records))
1381 header.close()
1382 for record in records:
1383 fields = []
1384 for i, field_name in enumerate(field_specs):
1385 fields.append("%-*s" % (sizes[i], record[field_name]))
1386 fd.write(''.join(fields) + '\n')
1387 finally:
1388 fd.close()
1389 fd = None
1390 return len(records)
1392 "returns record at physical_index[recno]"
1393 return yo._table[recno]
1394 - def goto(yo, criteria):
1395 """changes the record pointer to the first matching (non-deleted) record
1396 criteria should be either a tuple of tuple(value, field, func) triples,
1397 or an integer to go to"""
1398 if isinstance(criteria, int):
1399 if not -yo._meta.header.record_count <= criteria < yo._meta.header.record_count:
1400 raise IndexError("Record %d does not exist" % criteria)
1401 if criteria < 0:
1402 criteria += yo._meta.header.record_count
1403 yo._meta.current = criteria
1404 return yo.current()
1405 criteria = _normalize_tuples(tuples=criteria, length=3, filler=[_nop])
1406 specs = tuple([(field, func) for value, field, func in criteria])
1407 match = tuple([value for value, field, func in criteria])
1408 current = yo.current(index=True)
1409 matchlen = len(match)
1410 while not yo.Eof():
1411 record = yo.current()
1412 results = record(*specs)
1413 if results == match:
1414 return record
1415 return yo.goto(current)
1417 "returns True if name is a variable-length field type"
1418 return yo._meta[name]['type'] in yo._decimal_fields
1420 "returns True if name is a memo type field"
1421 return yo._meta[name]['type'] in yo._memotypes
1422 - def new(yo, filename, field_specs=None, codepage=None):
1436 "set record pointer to next (non-deleted) record, and return it"
1437 if yo.eof(_move=True):
1438 raise Eof()
1439 return yo.current()
1441 meta = yo._meta
1442 meta.inmemory = False
1443 meta.ondisk = True
1444 yo._read_only = False
1445 yo._meta_only = False
1446 if '_table' in dir(yo):
1447 del yo._table
1448 dfd = meta.dfd = open(meta.filename, 'r+b')
1449 dfd.seek(0)
1450 meta.header = header = yo._TableHeader(dfd.read(32))
1451 if not header.version in yo._supported_tables:
1452 dfd.close()
1453 dfd = None
1454 raise DbfError("Unsupported dbf type: %s [%x]" % (version_map.get(meta.header.version, 'Unknown: %s' % meta.header.version), ord(meta.header.version)))
1455 cp, sd, ld = _codepage_lookup(meta.header.codepage())
1456 meta.decoder = codecs.getdecoder(sd)
1457 meta.encoder = codecs.getencoder(sd)
1458 fieldblock = dfd.read(header.start - 32)
1459 for i in range(len(fieldblock)//32+1):
1460 fieldend = i * 32
1461 if fieldblock[fieldend] == '\x0d':
1462 break
1463 else:
1464 raise DbfError("corrupt field structure in header")
1465 if len(fieldblock[:fieldend]) % 32 != 0:
1466 raise DbfError("corrupt field structure in header")
1467 header.fields = fieldblock[:fieldend]
1468 header.extra = fieldblock[fieldend+1:]
1469 yo._initializeFields()
1470 yo._checkMemoIntegrity()
1471 meta.current = -1
1472 if len(yo) > 0:
1473 meta.current = 0
1474 dfd.seek(0)
1475
1476 - def pack(yo, _pack=True):
1477 "physically removes all deleted records"
1478 for dbfindex in yo._indexen:
1479 dbfindex.clear()
1480 newtable = []
1481 index = 0
1482 offset = 0
1483 for record in yo._table:
1484 found = False
1485 if record.has_been_deleted and _pack:
1486 for dbflist in yo._dbflists:
1487 if dbflist._purge(record, record.record_number - offset, 1):
1488 found = True
1489 record._recnum = -1
1490 else:
1491 record._recnum = index
1492 newtable.append(record)
1493 index += 1
1494 if found:
1495 offset += 1
1496 found = False
1497 yo._table.clear()
1498 for record in newtable:
1499 yo._table.append(record)
1500 yo._meta.header.record_count = index
1501 yo._current = -1
1502 yo._update_disk()
1503 yo.reindex()
1505 "set record pointer to previous (non-deleted) record, and return it"
1506 if yo.bof(_move=True):
1507 raise Bof
1508 return yo.current()
1509 - def query(yo, sql_command=None, python=None):
1510 "uses exec to perform queries on the table"
1511 if sql_command:
1512 return sql(yo, sql_command)
1513 elif python is None:
1514 raise DbfError("query: python parameter must be specified")
1515 possible = List(desc="%s --> %s" % (yo.filename, python), field_names=yo.field_names)
1516 yo._dbflists.add(possible)
1517 query_result = {}
1518 select = 'query_result["keep"] = %s' % python
1519 g = {}
1520 use_deleted = yo.use_deleted
1521 for record in yo:
1522 query_result['keep'] = False
1523 g['query_result'] = query_result
1524 exec select in g, record
1525 if query_result['keep']:
1526 possible.append(record)
1527 record.write_record()
1528 return possible
1530 for dbfindex in yo._indexen:
1531 dbfindex.reindex()
1533 "renames an existing field"
1534 if yo:
1535 yo.create_backup()
1536 if not oldname in yo._meta.fields:
1537 raise DbfError("field --%s-- does not exist -- cannot rename it." % oldname)
1538 if newname[0] == '_' or newname[0].isdigit() or not newname.replace('_','').isalnum():
1539 raise DbfError("field names cannot start with _ or digits, and can only contain the _, letters, and digits")
1540 newname = newname.lower()
1541 if newname in yo._meta.fields:
1542 raise DbfError("field --%s-- already exists" % newname)
1543 if len(newname) > 10:
1544 raise DbfError("maximum field name length is 10. '%s' is %d characters long." % (newname, len(newname)))
1545 yo._meta[newname] = yo._meta[oldname]
1546 yo._meta.fields[yo._meta.fields.index(oldname)] = newname
1547 yo._buildHeaderFields()
1548 yo._update_disk(headeronly=True)
1550 """resizes field (C only at this time)
1551 creates backup file, then modifies current structure"""
1552 if not 0 < new_size < 256:
1553 raise DbfError("new_size must be between 1 and 255 (use delete_fields to remove a field)")
1554 doomed = yo._list_fields(doomed)
1555 for victim in doomed:
1556 if victim not in yo._meta.fields:
1557 raise DbfError("field %s not in table -- resize aborted" % victim)
1558 all_records = [record for record in yo]
1559 yo.create_backup()
1560 for victim in doomed:
1561 start = yo._meta[victim]['start']
1562 end = yo._meta[victim]['end']
1563 eff_end = min(yo._meta[victim]['length'], new_size)
1564 yo._meta[victim]['length'] = new_size
1565 yo._meta[victim]['end'] = start + new_size
1566 blank = array('c', ' ' * new_size)
1567 for record in yo:
1568 new_data = blank[:]
1569 new_data[:eff_end] = record._data[start:start+eff_end]
1570 record._data = record._data[:start] + new_data + record._data[end:]
1571 for field in yo._meta.fields:
1572 if yo._meta[field]['start'] == end:
1573 end = yo._meta[field]['end']
1574 yo._meta[field]['start'] = start + new_size
1575 yo._meta[field]['end'] = start + new_size + yo._meta[field]['length']
1576 start = yo._meta[field]['end']
1577 yo._buildHeaderFields()
1578 yo._update_disk()
1579 - def size(yo, field):
1580 "returns size of field as a tuple of (length, decimals)"
1581 if field in yo:
1582 return (yo._meta[field]['length'], yo._meta[field]['decimals'])
1583 raise DbfError("%s is not a field in %s" % (field, yo.filename))
1585 """return list of fields suitable for creating same table layout
1586 @param fields: list of fields or None for all fields"""
1587 field_specs = []
1588 fields = yo._list_fields(fields)
1589 try:
1590 for name in fields:
1591 field_specs.append(yo._fieldLayout(yo.field_names.index(name)))
1592 except ValueError:
1593 raise DbfError("field --%s-- does not exist" % name)
1594 return field_specs
1595 - def top(yo, get_record=False):
1596 """sets record pointer to top of table; if get_record, seeks to and returns first (non-deleted) record
1597 DbfError if table is empty
1598 Eof if all records are deleted and use_deleted is False"""
1599 yo._meta.current = -1
1600 if get_record:
1601 try:
1602 return yo.next()
1603 except Eof:
1604 yo._meta.current = -1
1605 raise Bof()
1606 - def type(yo, field):
1607 "returns type of field"
1608 if field in yo:
1609 return yo._meta[field]['type']
1610 raise DbfError("%s is not a field in %s" % (field, yo.filename))
1611 - def zap(yo, areyousure=False):
1612 """removes all records from table -- this cannot be undone!
1613 areyousure must be True, else error is raised"""
1614 if areyousure:
1615 if yo._meta.inmemory:
1616 yo._table = []
1617 else:
1618 yo._table.clear()
1619 yo._meta.header.record_count = 0
1620 yo._current = -1
1621 yo._update_disk()
1622 else:
1623 raise DbfError("You must say you are sure to wipe the table")
1625 """Provides an interface for working with dBase III tables."""
1626 _version = 'dBase III Plus'
1627 _versionabbv = 'db3'
1628 _fieldtypes = {
1629 'C' : {'Type':'Character', 'Retrieve':io.retrieveCharacter, 'Update':io.updateCharacter, 'Blank':str, 'Init':io.addCharacter, 'Class':None},
1630 'D' : {'Type':'Date', 'Retrieve':io.retrieveDate, 'Update':io.updateDate, 'Blank':Date.today, 'Init':io.addDate, 'Class':None},
1631 'L' : {'Type':'Logical', 'Retrieve':io.retrieveLogical, 'Update':io.updateLogical, 'Blank':bool, 'Init':io.addLogical, 'Class':None},
1632 'M' : {'Type':'Memo', 'Retrieve':io.retrieveMemo, 'Update':io.updateMemo, 'Blank':str, 'Init':io.addMemo, 'Class':None},
1633 'N' : {'Type':'Numeric', 'Retrieve':io.retrieveNumeric, 'Update':io.updateNumeric, 'Blank':int, 'Init':io.addNumeric, 'Class':None} }
1634 _memoext = '.dbt'
1635 _memotypes = ('M',)
1636 _memoClass = _Db3Memo
1637 _yesMemoMask = '\x80'
1638 _noMemoMask = '\x7f'
1639 _fixed_fields = ('D','L','M')
1640 _variable_fields = ('C','N')
1641 _character_fields = ('C','M')
1642 _decimal_fields = ('N',)
1643 _numeric_fields = ('N',)
1644 _currency_fields = tuple()
1645 _dbfTableHeader = array('c', '\x00' * 32)
1646 _dbfTableHeader[0] = '\x03'
1647 _dbfTableHeader[8:10] = array('c', io.packShortInt(33))
1648 _dbfTableHeader[10] = '\x01'
1649 _dbfTableHeader[29] = '\x03'
1650 _dbfTableHeader = _dbfTableHeader.tostring()
1651 _dbfTableHeaderExtra = ''
1652 _supported_tables = ['\x03', '\x83']
1653 _read_only = False
1654 _meta_only = False
1655 _use_deleted = True
1657 "dBase III specific"
1658 if yo._meta.header.version == '\x83':
1659 try:
1660 yo._meta.memo = yo._memoClass(yo._meta)
1661 except:
1662 yo._meta.dfd.close()
1663 yo._meta.dfd = None
1664 raise
1665 if not yo._meta.ignorememos:
1666 for field in yo._meta.fields:
1667 if yo._meta[field]['type'] in yo._memotypes:
1668 if yo._meta.header.version != '\x83':
1669 yo._meta.dfd.close()
1670 yo._meta.dfd = None
1671 raise DbfError("Table structure corrupt: memo fields exist, header declares no memos")
1672 elif not os.path.exists(yo._meta.memoname):
1673 yo._meta.dfd.close()
1674 yo._meta.dfd = None
1675 raise DbfError("Table structure corrupt: memo fields exist without memo file")
1676 break
1678 "builds the FieldList of names, types, and descriptions"
1679 yo._meta.fields[:] = []
1680 offset = 1
1681 fieldsdef = yo._meta.header.fields
1682 if len(fieldsdef) % 32 != 0:
1683 raise DbfError("field definition block corrupt: %d bytes in size" % len(fieldsdef))
1684 if len(fieldsdef) // 32 != yo.field_count:
1685 raise DbfError("Header shows %d fields, but field definition block has %d fields" % (yo.field_count, len(fieldsdef)//32))
1686 for i in range(yo.field_count):
1687 fieldblock = fieldsdef[i*32:(i+1)*32]
1688 name = io.unpackStr(fieldblock[:11])
1689 type = fieldblock[11]
1690 if not type in yo._meta.fieldtypes:
1691 raise DbfError("Unknown field type: %s" % type)
1692 start = offset
1693 length = ord(fieldblock[16])
1694 offset += length
1695 end = start + length
1696 decimals = ord(fieldblock[17])
1697 flags = ord(fieldblock[18])
1698 yo._meta.fields.append(name)
1699 yo._meta[name] = {'type':type,'start':start,'length':length,'end':end,'decimals':decimals,'flags':flags}
1701 'Provides an interface for working with FoxPro 2 tables'
1702 _version = 'Foxpro'
1703 _versionabbv = 'fp'
1704 _fieldtypes = {
1705 'C' : {'Type':'Character', 'Retrieve':io.retrieveCharacter, 'Update':io.updateCharacter, 'Blank':str, 'Init':io.addCharacter, 'Class':None},
1706 'F' : {'Type':'Float', 'Retrieve':io.retrieveNumeric, 'Update':io.updateNumeric, 'Blank':float, 'Init':io.addVfpNumeric, 'Class':None},
1707 'N' : {'Type':'Numeric', 'Retrieve':io.retrieveNumeric, 'Update':io.updateNumeric, 'Blank':int, 'Init':io.addVfpNumeric, 'Class':None},
1708 'L' : {'Type':'Logical', 'Retrieve':io.retrieveLogical, 'Update':io.updateLogical, 'Blank':bool, 'Init':io.addLogical, 'Class':None},
1709 'D' : {'Type':'Date', 'Retrieve':io.retrieveDate, 'Update':io.updateDate, 'Blank':Date.today, 'Init':io.addDate, 'Class':None},
1710 'M' : {'Type':'Memo', 'Retrieve':io.retrieveMemo, 'Update':io.updateMemo, 'Blank':str, 'Init':io.addVfpMemo, 'Class':None},
1711 'G' : {'Type':'General', 'Retrieve':io.retrieveMemo, 'Update':io.updateMemo, 'Blank':str, 'Init':io.addMemo, 'Class':None},
1712 'P' : {'Type':'Picture', 'Retrieve':io.retrieveMemo, 'Update':io.updateMemo, 'Blank':str, 'Init':io.addMemo, 'Class':None},
1713 '0' : {'Type':'_NullFlags', 'Retrieve':io.unsupportedType, 'Update':io.unsupportedType, 'Blank':int, 'Init':None, 'Class':None} }
1714 _memoext = '.fpt'
1715 _memotypes = ('G','M','P')
1716 _memoClass = _VfpMemo
1717 _yesMemoMask = '\xf5'
1718 _noMemoMask = '\x03'
1719 _fixed_fields = ('B','D','G','I','L','M','P','T','Y')
1720 _variable_fields = ('C','F','N')
1721 _character_fields = ('C','M')
1722 _decimal_fields = ('F','N')
1723 _numeric_fields = ('F','N')
1724 _currency_fields = tuple()
1725 _supported_tables = ('\x03', '\xf5')
1726 _dbfTableHeader = array('c', '\x00' * 32)
1727 _dbfTableHeader[0] = '\x30'
1728 _dbfTableHeader[8:10] = array('c', io.packShortInt(33+263))
1729 _dbfTableHeader[10] = '\x01'
1730 _dbfTableHeader[29] = '\x03'
1731 _dbfTableHeader = _dbfTableHeader.tostring()
1732 _dbfTableHeaderExtra = '\x00' * 263
1733 _use_deleted = True
1735 if os.path.exists(yo._meta.memoname):
1736 try:
1737 yo._meta.memo = yo._memoClass(yo._meta)
1738 except:
1739 yo._meta.dfd.close()
1740 yo._meta.dfd = None
1741 raise
1742 if not yo._meta.ignorememos:
1743 for field in yo._meta.fields:
1744 if yo._meta[field]['type'] in yo._memotypes:
1745 if not os.path.exists(yo._meta.memoname):
1746 yo._meta.dfd.close()
1747 yo._meta.dfd = None
1748 raise DbfError("Table structure corrupt: memo fields exist without memo file")
1749 break
1751 "builds the FieldList of names, types, and descriptions"
1752 yo._meta.fields[:] = []
1753 offset = 1
1754 fieldsdef = yo._meta.header.fields
1755 if len(fieldsdef) % 32 != 0:
1756 raise DbfError("field definition block corrupt: %d bytes in size" % len(fieldsdef))
1757 if len(fieldsdef) // 32 != yo.field_count:
1758 raise DbfError("Header shows %d fields, but field definition block has %d fields" % (yo.field_count, len(fieldsdef)//32))
1759 for i in range(yo.field_count):
1760 fieldblock = fieldsdef[i*32:(i+1)*32]
1761 name = io.unpackStr(fieldblock[:11])
1762 type = fieldblock[11]
1763 if not type in yo._meta.fieldtypes:
1764 raise DbfError("Unknown field type: %s" % type)
1765 elif type == '0':
1766 return
1767 start = offset
1768 length = ord(fieldblock[16])
1769 offset += length
1770 end = start + length
1771 decimals = ord(fieldblock[17])
1772 flags = ord(fieldblock[18])
1773 yo._meta.fields.append(name)
1774 yo._meta[name] = {'type':type,'start':start,'length':length,'end':end,'decimals':decimals,'flags':flags}
1775
1777 'Provides an interface for working with Visual FoxPro 6 tables'
1778 _version = 'Visual Foxpro v6'
1779 _versionabbv = 'vfp'
1780 _fieldtypes = {
1781 'C' : {'Type':'Character', 'Retrieve':io.retrieveCharacter, 'Update':io.updateCharacter, 'Blank':str, 'Init':io.addCharacter, 'Class':None},
1782 'Y' : {'Type':'Currency', 'Retrieve':io.retrieveCurrency, 'Update':io.updateCurrency, 'Blank':Decimal(), 'Init':io.addVfpCurrency, 'Class':None},
1783 'B' : {'Type':'Double', 'Retrieve':io.retrieveDouble, 'Update':io.updateDouble, 'Blank':float, 'Init':io.addVfpDouble, 'Class':None},
1784 'F' : {'Type':'Float', 'Retrieve':io.retrieveNumeric, 'Update':io.updateNumeric, 'Blank':float, 'Init':io.addVfpNumeric, 'Class':None},
1785 'N' : {'Type':'Numeric', 'Retrieve':io.retrieveNumeric, 'Update':io.updateNumeric, 'Blank':int, 'Init':io.addVfpNumeric, 'Class':None},
1786 'I' : {'Type':'Integer', 'Retrieve':io.retrieveInteger, 'Update':io.updateInteger, 'Blank':int, 'Init':io.addVfpInteger, 'Class':None},
1787 'L' : {'Type':'Logical', 'Retrieve':io.retrieveLogical, 'Update':io.updateLogical, 'Blank':bool, 'Init':io.addLogical, 'Class':None},
1788 'D' : {'Type':'Date', 'Retrieve':io.retrieveDate, 'Update':io.updateDate, 'Blank':Date.today, 'Init':io.addDate, 'Class':None},
1789 'T' : {'Type':'DateTime', 'Retrieve':io.retrieveVfpDateTime, 'Update':io.updateVfpDateTime, 'Blank':DateTime.now, 'Init':io.addVfpDateTime, 'Class':None},
1790 'M' : {'Type':'Memo', 'Retrieve':io.retrieveVfpMemo, 'Update':io.updateVfpMemo, 'Blank':str, 'Init':io.addVfpMemo, 'Class':None},
1791 'G' : {'Type':'General', 'Retrieve':io.retrieveVfpMemo, 'Update':io.updateVfpMemo, 'Blank':str, 'Init':io.addVfpMemo, 'Class':None},
1792 'P' : {'Type':'Picture', 'Retrieve':io.retrieveVfpMemo, 'Update':io.updateVfpMemo, 'Blank':str, 'Init':io.addVfpMemo, 'Class':None},
1793 '0' : {'Type':'_NullFlags', 'Retrieve':io.unsupportedType, 'Update':io.unsupportedType, 'Blank':int, 'Init':None, 'Class':None} }
1794 _memoext = '.fpt'
1795 _memotypes = ('G','M','P')
1796 _memoClass = _VfpMemo
1797 _yesMemoMask = '\x30'
1798 _noMemoMask = '\x30'
1799 _fixed_fields = ('B','D','G','I','L','M','P','T','Y')
1800 _variable_fields = ('C','F','N')
1801 _character_fields = ('C','M')
1802 _decimal_fields = ('F','N')
1803 _numeric_fields = ('B','F','I','N','Y')
1804 _currency_fields = ('Y',)
1805 _supported_tables = ('\x30',)
1806 _dbfTableHeader = array('c', '\x00' * 32)
1807 _dbfTableHeader[0] = '\x30'
1808 _dbfTableHeader[8:10] = array('c', io.packShortInt(33+263))
1809 _dbfTableHeader[10] = '\x01'
1810 _dbfTableHeader[29] = '\x03'
1811 _dbfTableHeader = _dbfTableHeader.tostring()
1812 _dbfTableHeaderExtra = '\x00' * 263
1813 _use_deleted = True
1815 if os.path.exists(yo._meta.memoname):
1816 try:
1817 yo._meta.memo = yo._memoClass(yo._meta)
1818 except:
1819 yo._meta.dfd.close()
1820 yo._meta.dfd = None
1821 raise
1822 if not yo._meta.ignorememos:
1823 for field in yo._meta.fields:
1824 if yo._meta[field]['type'] in yo._memotypes:
1825 if not os.path.exists(yo._meta.memoname):
1826 yo._meta.dfd.close()
1827 yo._meta.dfd = None
1828 raise DbfError("Table structure corrupt: memo fields exist without memo file")
1829 break
1831 "builds the FieldList of names, types, and descriptions"
1832 yo._meta.fields[:] = []
1833 offset = 1
1834 fieldsdef = yo._meta.header.fields
1835 for i in range(yo.field_count):
1836 fieldblock = fieldsdef[i*32:(i+1)*32]
1837 name = io.unpackStr(fieldblock[:11])
1838 type = fieldblock[11]
1839 if not type in yo._meta.fieldtypes:
1840 raise DbfError("Unknown field type: %s" % type)
1841 elif type == '0':
1842 return
1843 start = io.unpackLongInt(fieldblock[12:16])
1844 length = ord(fieldblock[16])
1845 offset += length
1846 end = start + length
1847 decimals = ord(fieldblock[17])
1848 flags = ord(fieldblock[18])
1849 yo._meta.fields.append(name)
1850 yo._meta[name] = {'type':type,'start':start,'length':length,'end':end,'decimals':decimals,'flags':flags}
1851 -class List(object):
1852 "list of Dbf records, with set-like behavior"
1853 _desc = ''
1854 - def __init__(yo, new_records=None, desc=None, key=None, field_names=None):
1855 yo.field_names = field_names
1856 yo._list = []
1857 yo._set = set()
1858 if key is not None:
1859 yo.key = key
1860 if key.__doc__ is None:
1861 key.__doc__ = 'unknown'
1862 key = yo.key
1863 yo._current = -1
1864 if isinstance(new_records, yo.__class__) and key is new_records.key:
1865 yo._list = new_records._list[:]
1866 yo._set = new_records._set.copy()
1867 yo._current = 0
1868 elif new_records is not None:
1869 for record in new_records:
1870 value = key(record)
1871 item = (record.record_table, record.record_number, value)
1872 if value not in yo._set:
1873 yo._set.add(value)
1874 yo._list.append(item)
1875 yo._current = 0
1876 if desc is not None:
1877 yo._desc = desc
1879 key = yo.key
1880 if isinstance(other, (DbfTable, list)):
1881 other = yo.__class__(other, key=key)
1882 if isinstance(other, yo.__class__):
1883 result = yo.__class__()
1884 result._set = yo._set.copy()
1885 result._list[:] = yo._list[:]
1886 result.key = yo.key
1887 if key is other.key:
1888 for item in other._list:
1889 if item[2] not in result._set:
1890 result._set.add(item[2])
1891 result._list.append(item)
1892 else:
1893 for rec in other:
1894 value = key(rec)
1895 if value not in result._set:
1896 result._set.add(value)
1897 result._list.append((rec.record_table, rec.record_number, value))
1898 result._current = 0 if result else -1
1899 return result
1900 return NotImplemented
1902 if isinstance(record, tuple):
1903 item = record
1904 else:
1905 item = yo.key(record)
1906 return item in yo._set
1908 if isinstance(key, int):
1909 item = yo._list.pop[key]
1910 yo._set.remove(item[2])
1911 elif isinstance(key, slice):
1912 yo._set.difference_update([item[2] for item in yo._list[key]])
1913 yo._list.__delitem__(key)
1914 else:
1915 raise TypeError
1917 if isinstance(key, int):
1918 count = len(yo._list)
1919 if not -count <= key < count:
1920 raise IndexError("Record %d is not in list." % key)
1921 return yo._get_record(*yo._list[key])
1922 elif isinstance(key, slice):
1923 result = yo.__class__()
1924 result._list[:] = yo._list[key]
1925 result._set = set(result._list)
1926 result.key = yo.key
1927 result._current = 0 if result else -1
1928 return result
1929 else:
1930 raise TypeError('indices must be integers')
1932 return (table.get_record(recno) for table, recno, value in yo._list)
1934 return len(yo._list)
1940 if yo._desc:
1941 return "%s(key=%s - %s - %d records)" % (yo.__class__, yo.key.__doc__, yo._desc, len(yo._list))
1942 else:
1943 return "%s(key=%s - %d records)" % (yo.__class__, yo.key.__doc__, len(yo._list))
1945 key = yo.key
1946 if isinstance(other, (DbfTable, list)):
1947 other = yo.__class__(other, key=key)
1948 if isinstance(other, yo.__class__):
1949 result = yo.__class__()
1950 result._list[:] = other._list[:]
1951 result._set = other._set.copy()
1952 result.key = key
1953 lost = set()
1954 if key is other.key:
1955 for item in yo._list:
1956 if item[2] in result._list:
1957 result._set.remove(item[2])
1958 lost.add(item)
1959 else:
1960 for rec in other:
1961 value = key(rec)
1962 if value in result._set:
1963 result._set.remove(value)
1964 lost.add((rec.record_table, rec.record_number, value))
1965 result._list = [item for item in result._list if item not in lost]
1966 result._current = 0 if result else -1
1967 return result
1968 return NotImplemented
1970 key = yo.key
1971 if isinstance(other, (DbfTable, list)):
1972 other = yo.__class__(other, key=key)
1973 if isinstance(other, yo.__class__):
1974 result = yo.__class__()
1975 result._list[:] = yo._list[:]
1976 result._set = yo._set.copy()
1977 result.key = key
1978 lost = set()
1979 if key is other.key:
1980 for item in other._list:
1981 if item[2] in result._set:
1982 result._set.remove(item[2])
1983 lost.add(item[2])
1984 else:
1985 for rec in other:
1986 value = key(rec)
1987 if value in result._set:
1988 result._set.remove(value)
1989 lost.add(value)
1990 result._list = [item for item in result._list if item[2] not in lost]
1991 result._current = 0 if result else -1
1992 return result
1993 return NotImplemented
1995 if item[2] not in yo._set:
1996 yo._set.add(item[2])
1997 yo._list.append(item)
1998 - def _get_record(yo, table=None, rec_no=None, value=None):
1999 if table is rec_no is None:
2000 table, rec_no, value = yo._list[yo._current]
2001 return table.get_record(rec_no)
2002 - def _purge(yo, record, old_record_number, offset):
2003 partial = record.record_table, old_record_number
2004 records = sorted(yo._list, key=lambda item: (item[0], item[1]))
2005 for item in records:
2006 if partial == item[:2]:
2007 found = True
2008 break
2009 elif partial[0] is item[0] and partial[1] < item[1]:
2010 found = False
2011 break
2012 else:
2013 found = False
2014 if found:
2015 yo._list.pop(yo._list.index(item))
2016 yo._set.remove(item[2])
2017 start = records.index(item) + found
2018 for item in records[start:]:
2019 if item[0] is not partial[0]:
2020 break
2021 i = yo._list.index(item)
2022 yo._set.remove(item[2])
2023 item = item[0], (item[1] - offset), item[2]
2024 yo._list[i] = item
2025 yo._set.add(item[2])
2026 return found
2033 if yo._list:
2034 yo._current = len(yo._list) - 1
2035 return yo._get_record()
2036 raise DbfError("dbf.List is empty")
2038 yo._list = []
2039 yo._set = set()
2040 yo._current = -1
2042 if yo._current < 0:
2043 raise Bof()
2044 elif yo._current == len(yo._list):
2045 raise Eof()
2046 return yo._get_record()
2047 - def extend(yo, new_records):
2063 - def goto(yo, index_number):
2064 if yo._list:
2065 if 0 <= index_number <= len(yo._list):
2066 yo._current = index_number
2067 return yo._get_record()
2068 raise DbfError("index %d not in dbf.List of %d records" % (index_number, len(yo._list)))
2069 raise DbfError("dbf.List is empty")
2070 - def index(yo, sort=None, reverse=False):
2071 "sort= ((field_name, func), (field_name, func),) | 'ORIGINAL'"
2072 if sort is None:
2073 results = []
2074 for field, func in yo._meta.index:
2075 results.append("%s(%s)" % (func.__name__, field))
2076 return ', '.join(results + ['reverse=%s' % yo._meta.index_reversed])
2077 yo._meta.index_reversed = reverse
2078 if sort == 'ORIGINAL':
2079 yo._index = range(yo._meta.header.record_count)
2080 yo._meta.index = 'ORIGINAL'
2081 if reverse:
2082 yo._index.reverse()
2083 return
2084 new_sort = _normalize_tuples(tuples=sort, length=2, filler=[_nop])
2085 yo._meta.index = tuple(new_sort)
2086 yo._meta.orderresults = [''] * len(yo)
2087 for record in yo:
2088 yo._meta.orderresults[record.record_number] = record()
2089 yo._index.sort(key=lambda i: yo._meta.orderresults[i], reverse=reverse)
2090 - def index(yo, record, start=None, stop=None):
2102 - def key(yo, record):
2106 if yo._current < len(yo._list):
2107 yo._current += 1
2108 if yo._current < len(yo._list):
2109 return yo._get_record()
2110 raise Eof()
2111 - def pop(yo, index=None):
2112 if index is None:
2113 table, recno, value = yo._list.pop()
2114 else:
2115 table, recno, value = yo._list.pop(index)
2116 yo._set.remove(value)
2117 return yo._get_record(table, recno, value)
2119 if yo._current >= 0:
2120 yo._current -= 1
2121 if yo._current > -1:
2122 return yo._get_record()
2123 raise Bof()
2131 if yo._list:
2132 yo._current = 0
2133 return yo._get_record()
2134 raise DbfError("dbf.List is empty")
2135 - def sort(yo, key=None, reverse=False):
2139
2151 "returns records using this index"
2153 yo.table = table
2154 yo.records = records
2155 yo.index = 0
2167 - def __init__(yo, table, key, field_names=None):
2168 yo._table = table
2169 yo._values = []
2170 yo._rec_by_val = []
2171 yo._records = {}
2172 yo.__doc__ = key.__doc__ or 'unknown'
2173 yo.key = key
2174 yo.field_names = field_names or table.field_names
2175 for record in table:
2176 value = key(record)
2177 if value is DoNotIndex:
2178 continue
2179 rec_num = record.record_number
2180 if not isinstance(value, tuple):
2181 value = (value, )
2182 vindex = bisect_right(yo._values, value)
2183 yo._values.insert(vindex, value)
2184 yo._rec_by_val.insert(vindex, rec_num)
2185 yo._records[rec_num] = value
2186 table._indexen.add(yo)
2188 rec_num = record.record_number
2189 if rec_num in yo._records:
2190 value = yo._records[rec_num]
2191 vindex = bisect_left(yo._values, value)
2192 yo._values.pop(vindex)
2193 yo._rec_by_val.pop(vindex)
2194 value = yo.key(record)
2195 if value is DoNotIndex:
2196 return
2197 if not isinstance(value, tuple):
2198 value = (value, )
2199 vindex = bisect_right(yo._values, value)
2200 yo._values.insert(vindex, value)
2201 yo._rec_by_val.insert(vindex, rec_num)
2202 yo._records[rec_num] = value
2204 if isinstance(match, _DbfRecord):
2205 if match.record_table is yo._table:
2206 return match.record_number in yo._records
2207 match = yo.key(match)
2208 elif not isinstance(match, tuple):
2209 match = (match, )
2210 return yo.find(match) != -1
2212 if isinstance(key, int):
2213 count = len(yo._values)
2214 if not -count <= key < count:
2215 raise IndexError("Record %d is not in list." % key)
2216 rec_num = yo._rec_by_val[key]
2217 return yo._table.get_record(rec_num)
2218 elif isinstance(key, slice):
2219 result = List(field_names=yo._table.field_names)
2220 yo._table._dbflists.add(result)
2221 start, stop, step = key.start, key.stop, key.step
2222 if start is None: start = 0
2223 if stop is None: stop = len(yo._rec_by_val)
2224 if step is None: step = 1
2225 for loc in range(start, stop, step):
2226 record = yo._table.get_record(yo._rec_by_val[loc])
2227 result._maybe_add(item=(yo._table, yo._rec_by_val[loc], result.key(record)))
2228 result._current = 0 if result else -1
2229 return result
2230 elif isinstance (key, (str, unicode, tuple, _DbfRecord)):
2231 if isinstance(key, _DbfRecord):
2232 key = yo.key(key)
2233 elif not isinstance(key, tuple):
2234 key = (key, )
2235 loc = yo.find(key)
2236 if loc == -1:
2237 raise KeyError(key)
2238 return yo._table.get_record(yo._rec_by_val[loc])
2239 else:
2240 raise TypeError('indices must be integers, match objects must by strings or tuples')
2244 yo._table.close()
2245 yo._values[:] = []
2246 yo._rec_by_val[:] = []
2247 yo._records.clear()
2248 return False
2252 return len(yo._records)
2254 target = target[:len(match)]
2255 if isinstance(match[-1], (str, unicode)):
2256 target = list(target)
2257 target[-1] = target[-1][:len(match[-1])]
2258 target = tuple(target)
2259 return target == match
2261 value = yo._records.get(rec_num)
2262 if value is not None:
2263 vindex = bisect_left(yo._values, value)
2264 del yo._records[rec_num]
2265 yo._values.pop(vindex)
2266 yo._rec_by_val.pop(vindex)
2267 - def _search(yo, match, lo=0, hi=None):
2268 if hi is None:
2269 hi = len(yo._values)
2270 return bisect_left(yo._values, match, lo, hi)
2272 "removes all entries from index"
2273 yo._values[:] = []
2274 yo._rec_by_val[:] = []
2275 yo._records.clear()
2278 - def find(yo, match, partial=False):
2279 "returns numeric index of (partial) match, or -1"
2280 if isinstance(match, _DbfRecord):
2281 if match.record_number in yo._records:
2282 return yo._values.index(yo._records[match.record_number])
2283 else:
2284 return -1
2285 if not isinstance(match, tuple):
2286 match = (match, )
2287 loc = yo._search(match)
2288 while loc < len(yo._values) and yo._values[loc] == match:
2289 if not yo._table.use_deleted and yo._table.get_record(yo._rec_by_val[loc]).has_been_deleted:
2290 loc += 1
2291 continue
2292 return loc
2293 if partial:
2294 while loc < len(yo._values) and yo._partial_match(yo._values[loc], match):
2295 if not yo._table.use_deleted and yo._table.get_record(yo._rec_by_val[loc]).has_been_deleted:
2296 loc += 1
2297 continue
2298 return loc
2299 return -1
2301 "returns numeric index of either (partial) match, or position of where match would be"
2302 if isinstance(match, _DbfRecord):
2303 if match.record_number in yo._records:
2304 return yo._values.index(yo._records[match.record_number])
2305 else:
2306 match = yo.key(match)
2307 if not isinstance(match, tuple):
2308 match = (match, )
2309 loc = yo._search(match)
2310 return loc
2311 - def index(yo, match, partial=False):
2312 "returns numeric index of (partial) match, or raises ValueError"
2313 loc = yo.find(match, partial)
2314 if loc == -1:
2315 if isinstance(match, _DbfRecord):
2316 raise ValueError("table <%s> record [%d] not in index <%s>" % (yo._table.filename, match.record_number, yo.__doc__))
2317 else:
2318 raise ValueError("match criteria <%s> not in index" % (match, ))
2319 return loc
2321 "reindexes all records"
2322 for record in yo._table:
2323 yo(record)
2324 - def query(yo, sql_command=None, python=None):
2325 """recognized sql commands are SELECT, UPDATE, REPLACE, INSERT, DELETE, and RECALL"""
2326 if sql_command:
2327 return sql(yo, sql_command)
2328 elif python is None:
2329 raise DbfError("query: python parameter must be specified")
2330 possible = List(desc="%s --> %s" % (yo._table.filename, python), field_names=yo._table.field_names)
2331 yo._table._dbflists.add(possible)
2332 query_result = {}
2333 select = 'query_result["keep"] = %s' % python
2334 g = {}
2335 for record in yo:
2336 query_result['keep'] = False
2337 g['query_result'] = query_result
2338 exec select in g, record
2339 if query_result['keep']:
2340 possible.append(record)
2341 record.write_record()
2342 return possible
2343 - def search(yo, match, partial=False):
2344 "returns dbf.List of all (partially) matching records"
2345 result = List(field_names=yo._table.field_names)
2346 yo._table._dbflists.add(result)
2347 if not isinstance(match, tuple):
2348 match = (match, )
2349 loc = yo._search(match)
2350 if loc == len(yo._values):
2351 return result
2352 while loc < len(yo._values) and yo._values[loc] == match:
2353 record = yo._table.get_record(yo._rec_by_val[loc])
2354 if not yo._table.use_deleted and record.has_been_deleted:
2355 loc += 1
2356 continue
2357 result._maybe_add(item=(yo._table, yo._rec_by_val[loc], result.key(record)))
2358 loc += 1
2359 if partial:
2360 while loc < len(yo._values) and yo._partial_match(yo._values[loc], match):
2361 record = yo._table.get_record(yo._rec_by_val[loc])
2362 if not yo._table.use_deleted and record.has_been_deleted:
2363 loc += 1
2364 continue
2365 result._maybe_add(item=(yo._table, yo._rec_by_val[loc], result.key(record)))
2366 loc += 1
2367 return result
2368
2369 csv.register_dialect('dbf', DbfCsv)
2370
2371 -def sql_select(records, chosen_fields, condition, field_names):
2372 if chosen_fields != '*':
2373 field_names = chosen_fields.replace(' ','').split(',')
2374 result = condition(records)
2375 result.modified = 0, 'record' + ('','s')[len(result)>1]
2376 result.field_names = field_names
2377 return result
2378
2379 -def sql_update(records, command, condition, field_names):
2380 possible = condition(records)
2381 modified = sql_cmd(command, field_names)(possible)
2382 possible.modified = modified, 'record' + ('','s')[modified>1]
2383 return possible
2384
2385 -def sql_delete(records, dead_fields, condition, field_names):
2386 deleted = condition(records)
2387 deleted.modified = len(deleted), 'record' + ('','s')[len(deleted)>1]
2388 deleted.field_names = field_names
2389 if dead_fields == '*':
2390 for record in deleted:
2391 record.delete_record()
2392 record.write_record()
2393 else:
2394 keep = [f for f in field_names if f not in dead_fields.replace(' ','').split(',')]
2395 for record in deleted:
2396 record.reset_record(keep_fields=keep)
2397 record.write_record()
2398 return deleted
2399
2400 -def sql_recall(records, all_fields, condition, field_names):
2421
2422 -def sql_add(records, new_fields, condition, field_names):
2432
2433 -def sql_drop(records, dead_fields, condition, field_names):
2443
2444 -def sql_pack(records, command, condition, field_names):
2454
2455 -def sql_resize(records, fieldname_newsize, condition, field_names):
2456 tables = set()
2457 possible = condition(records)
2458 for record in possible:
2459 tables.add(record.record_table)
2460 fieldname, newsize = fieldname_newsize.split()
2461 newsize = int(newsize)
2462 for table in tables:
2463 table.resize_field(fieldname, newsize)
2464 possible.modified = len(tables), 'table' + ('','s')[len(tables)>1]
2465 possible.field_names = field_names
2466 return possible
2467
2468 sql_functions = {
2469 'select' : sql_select,
2470 'update' : sql_update,
2471 'replace': sql_update,
2472 'insert' : None,
2473 'delete' : sql_delete,
2474 'recall' : sql_recall,
2475 'add' : sql_add,
2476 'drop' : sql_drop,
2477 'count' : None,
2478 'pack' : sql_pack,
2479 'resize' : sql_resize,
2480 }
2483 "creates a function matching the sql criteria"
2484 function = """def func(records):
2485 \"\"\"%s\"\"\"
2486 matched = List(field_names=records[0].field_names)
2487 for rec in records:
2488 %s
2489
2490 if %s:
2491 matched.append(rec)
2492 return matched"""
2493 fields = []
2494 for field in records[0].field_names:
2495 if field in criteria:
2496 fields.append(field)
2497 fields = '\n '.join(['%s = rec.%s' % (field, field) for field in fields])
2498 g = dbf.sql_user_functions.copy()
2499 g['List'] = List
2500 function %= (criteria, fields, criteria)
2501 print function
2502 exec function in g
2503 return g['func']
2504
2505 -def sql_cmd(command, field_names):
2506 "creates a function matching to apply command to each record in records"
2507 function = """def func(records):
2508 \"\"\"%s\"\"\"
2509 changed = 0
2510 for rec in records:
2511 %s
2512
2513 %s
2514
2515 %s
2516 changed += rec.write_record()
2517 return changed"""
2518 fields = []
2519 for field in field_names:
2520 if field in command:
2521 fields.append(field)
2522 pre_fields = '\n '.join(['%s = rec.%s' % (field, field) for field in fields])
2523 post_fields = '\n '.join(['rec.%s = %s' % (field, field) for field in fields])
2524 g = dbf.sql_user_functions.copy()
2525 if '=' not in command and ' with ' in command.lower():
2526 offset = command.lower().index(' with ')
2527 command = command[:offset] + ' = ' + command[offset+6:]
2528 function %= (command, pre_fields, command, post_fields)
2529 print function
2530 exec function in g
2531 return g['func']
2532
2533 -def sql(records, command):
2534 """recognized sql commands are SELECT, UPDATE | REPLACE, DELETE, RECALL, ADD, DROP"""
2535 sql_command = command
2536 if ' where ' in command:
2537 command, condition = command.split(' where ', 1)
2538 condition = sql_criteria(records, condition)
2539 else:
2540 def condition(records):
2541 return records[:]
2542 name, command = command.split(' ', 1)
2543 command = command.strip()
2544 name = name.lower()
2545 field_names = records[0].field_names
2546 if sql_functions.get(name) is None:
2547 raise DbfError('unknown SQL command: %s' % name.upper())
2548 result = sql_functions[name](records, command, condition, field_names)
2549 tables = set()
2550 for record in result:
2551 tables.add(record.record_table)
2552 for list_table in tables:
2553 list_table._dbflists.add(result)
2554 return result
2556 "returns parameter unchanged"
2557 return value
2559 "ensures each tuple is the same length, using filler[-missing] for the gaps"
2560 final = []
2561 for t in tuples:
2562 if len(t) < length:
2563 final.append( tuple([item for item in t] + filler[len(t)-length:]) )
2564 else:
2565 final.append(t)
2566 return tuple(final)
2568 if cp not in code_pages:
2569 for code_page in sorted(code_pages.keys()):
2570 sd, ld = code_pages[code_page]
2571 if cp == sd or cp == ld:
2572 if sd is None:
2573 raise DbfError("Unsupported codepage: %s" % ld)
2574 cp = code_page
2575 break
2576 else:
2577 raise DbfError("Unsupported codepage: %s" % cp)
2578 sd, ld = code_pages[cp]
2579 return cp, sd, ld
2580 -def ascii(new_setting=None):
2587 -def codepage(cp=None):
2588 "get/set default codepage for any new tables"
2589 global default_codepage
2590 cp, sd, ld = _codepage_lookup(cp or default_codepage)
2591 default_codepage = sd
2592 return "%s (LDID: 0x%02x - %s)" % (sd, ord(cp), ld)
2600 version = 'dBase IV w/memos (non-functional)'
2601 _versionabbv = 'db4'
2602 _fieldtypes = {
2603 'C' : {'Type':'Character', 'Retrieve':io.retrieveCharacter, 'Update':io.updateCharacter, 'Blank':str, 'Init':io.addCharacter},
2604 'Y' : {'Type':'Currency', 'Retrieve':io.retrieveCurrency, 'Update':io.updateCurrency, 'Blank':Decimal(), 'Init':io.addVfpCurrency},
2605 'B' : {'Type':'Double', 'Retrieve':io.retrieveDouble, 'Update':io.updateDouble, 'Blank':float, 'Init':io.addVfpDouble},
2606 'F' : {'Type':'Float', 'Retrieve':io.retrieveNumeric, 'Update':io.updateNumeric, 'Blank':float, 'Init':io.addVfpNumeric},
2607 'N' : {'Type':'Numeric', 'Retrieve':io.retrieveNumeric, 'Update':io.updateNumeric, 'Blank':int, 'Init':io.addVfpNumeric},
2608 'I' : {'Type':'Integer', 'Retrieve':io.retrieveInteger, 'Update':io.updateInteger, 'Blank':int, 'Init':io.addVfpInteger},
2609 'L' : {'Type':'Logical', 'Retrieve':io.retrieveLogical, 'Update':io.updateLogical, 'Blank':bool, 'Init':io.addLogical},
2610 'D' : {'Type':'Date', 'Retrieve':io.retrieveDate, 'Update':io.updateDate, 'Blank':Date.today, 'Init':io.addDate},
2611 'T' : {'Type':'DateTime', 'Retrieve':io.retrieveVfpDateTime, 'Update':io.updateVfpDateTime, 'Blank':DateTime.now, 'Init':io.addVfpDateTime},
2612 'M' : {'Type':'Memo', 'Retrieve':io.retrieveMemo, 'Update':io.updateMemo, 'Blank':str, 'Init':io.addMemo},
2613 'G' : {'Type':'General', 'Retrieve':io.retrieveMemo, 'Update':io.updateMemo, 'Blank':str, 'Init':io.addMemo},
2614 'P' : {'Type':'Picture', 'Retrieve':io.retrieveMemo, 'Update':io.updateMemo, 'Blank':str, 'Init':io.addMemo},
2615 '0' : {'Type':'_NullFlags', 'Retrieve':io.unsupportedType, 'Update':io.unsupportedType, 'Blank':int, 'Init':None} }
2616 _memoext = '.dbt'
2617 _memotypes = ('G','M','P')
2618 _memoClass = _VfpMemo
2619 _yesMemoMask = '\x8b'
2620 _noMemoMask = '\x04'
2621 _fixed_fields = ('B','D','G','I','L','M','P','T','Y')
2622 _variable_fields = ('C','F','N')
2623 _character_fields = ('C','M')
2624 _decimal_fields = ('F','N')
2625 _numeric_fields = ('B','F','I','N','Y')
2626 _currency_fields = ('Y',)
2627 _supported_tables = ('\x04', '\x8b')
2628 _dbfTableHeader = ['\x00'] * 32
2629 _dbfTableHeader[0] = '\x8b'
2630 _dbfTableHeader[10] = '\x01'
2631 _dbfTableHeader[29] = '\x03'
2632 _dbfTableHeader = ''.join(_dbfTableHeader)
2633 _dbfTableHeaderExtra = ''
2634 _use_deleted = True
2636 "dBase III specific"
2637 if yo._meta.header.version == '\x8b':
2638 try:
2639 yo._meta.memo = yo._memoClass(yo._meta)
2640 except:
2641 yo._meta.dfd.close()
2642 yo._meta.dfd = None
2643 raise
2644 if not yo._meta.ignorememos:
2645 for field in yo._meta.fields:
2646 if yo._meta[field]['type'] in yo._memotypes:
2647 if yo._meta.header.version != '\x8b':
2648 yo._meta.dfd.close()
2649 yo._meta.dfd = None
2650 raise DbfError("Table structure corrupt: memo fields exist, header declares no memos")
2651 elif not os.path.exists(yo._meta.memoname):
2652 yo._meta.dfd.close()
2653 yo._meta.dfd = None
2654 raise DbfError("Table structure corrupt: memo fields exist without memo file")
2655 break
2656