home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyc (Python 2.5)
-
- """
- KirbyBase v1.8.1 (applied patch introduced in v1.8.2)
-
- Contains classes for a plain-text, client-server dbms.
-
- NOTE: This copy has been modified from the standard distribution of KirbyBase.
- To get the complete distribution of KirbyBase, please visit:
- http://www.netpromi.com/kirbybase.html
-
- Classes:
- KirbyBase - database class
- KBError - exceptions
-
- Example:
- from db import *
-
- db = KirbyBase()
- db.create('plane.tbl', ['name:str', 'country:str', 'speed:int',
- 'range:int'])
- db.insert('plane.tbl', ['P-51', 'USA', 403, 1201])
- db.insert('plane.tbl', ['P-38', 'USA', 377, 999])
- db.select('plane.tbl', ['country', 'speed'], ['USA', '>400'])
- db.update('plane.tbl', ['country'], ['USA'], ['United States'],
- ['country'])
- db.delete('plane.tbl', ['speed'], ['<400'])
- db.close()
-
- Author:
- Jamey Cribbs -- jcribbs@twmi.rr.com
- www.netpromi.com
-
- License:
- KirbyBase is licensed under the Python Software Foundation License.
- KirbyBase carries no warranty! Use at your own risk.
- """
- from __future__ import generators
- import re
- import os.path as os
- import datetime
- import cStringIO
- import operator
-
- class KirbyBase:
- """Database Management System.
-
- Public Methods:
- __init__ - Create an instance of database.
- close - Close database.
- create - Create a table.
- insert - Insert a record into a table.
- insertBatch - Insert a list of records into a table.
- update - Update a table.
- delete - Delete record(s) from a table.
- select - select record(s) from a table.
- pack - remove deleted records from a table.
- validate - validate data in table records.
- drop - Remove a table.
- getFieldNames - Get a list of a table's field names.
- getFieldTypes - Get a list of a table's field types.
- len - Total number of records in table.
- """
-
- def __init__(self):
- '''Create an instance of the database and return a reference to it.
- '''
- self.connect_type = type
- self.encodeRegExp = re.compile('\\n|\\r|\\032|\\|')
- self.unencodeRegExp = re.compile('&linefeed;|&carriage_return;|&substitute;|&pipe;')
- self.cmpFuncs = {
- '<': operator.lt,
- '<=': operator.le,
- '>=': operator.ge,
- '>': operator.gt,
- '==': operator.eq,
- '!=': operator.ne,
- '<>': operator.ne }
- self.strToTypes = {
- 'int': int,
- 'Integer': int,
- 'float': float,
- 'Float': float,
- 'datetime.date': datetime.date,
- 'Date': datetime.date,
- 'datetime.datetime': datetime.datetime,
- 'DateTime': datetime.datetime,
- 'bool': bool,
- 'Boolean': bool,
- 'str': str,
- 'String': str }
-
-
- def close(self):
- '''Close connection to database server.
- '''
- pass
-
-
- def create(self, name, fields):
- """Create a new table and return True on success.
-
- Arguments:
- name - physical filename, including path, that will hold
- table.
- fields - list holding strings made up of multiple fieldname,
- fieldtype pairs (i.e. ['plane:str','speed:int']).
- Valid fieldtypes are: str, int, float, datetime.date,
- datetime.datetime, bool or, for compatibility with
- the Ruby version of KirbyBase use String, Integer,
- Float, Date, DateTime, and Boolean.
-
- Returns True if no exceptions are raised.
- """
- if os.path.exists(name):
- raise KBError(name + ' already exists!')
-
- for y in fields:
- pass
-
- header_rec = list([
- '000000',
- '000000',
- 'recno:int'] + fields)
- fptr = self._openTable(name, 'w')
- fptr.write('|'.join(header_rec) + '\n')
- self._closeTable(fptr)
- return True
-
-
- def insert(self, name, values):
- '''Insert a new record into table, return unique record number.
-
- Arguments:
- name - physical file name, including path, that holds table.
- values - list, dictionary, or object containing field values
- of new record.
-
- Returns unique record number assigned to new record when it is
- created.
- '''
- fptr = self._openTable(name, 'r+')
- self._updateHeaderVars(fptr)
- record = self._convertInput(values)
- self._validateUpdateCriteria(record, self.field_names[1:])
-
- try:
- rec_no = self._incrRecnoCounter(fptr)
- record.insert(0, rec_no)
- 'end'('|'.join, map, self._encodeString([]([], [ str(item) for item in record ])))
- finally:
- self._closeTable(fptr)
-
- return rec_no
-
-
- def insertBatch(self, name, batchRecords):
- '''Insert a batch of records into table, return a list of rec #s.
-
- Arguments:
- name - physical file name, including path, that holds
- table.
- batchRecords - list of records. Each record can be a list, a
- dictionary, or an object containing field values
- of new record.
-
- Returns list of unique record numbers assigned.
- '''
- fptr = self._openTable(name, 'r')
- self._updateHeaderVars(fptr)
- self._closeTable(fptr)
- records = []
- for values in batchRecords:
- record = self._convertInput(values)
- self._validateUpdateCriteria(record, self.field_names[1:])
- records.append(record)
-
- rec_nos = []
- fptr = self._openTable(name, 'r+')
-
- try:
- for record in records:
- rec_no = self._incrRecnoCounter(fptr)
- record.insert(0, rec_no)
- 'end'('|'.join, map, self._encodeString([]([], [ str(item) for item in record ])))
- rec_nos.append(rec_no)
- finally:
- self._closeTable(fptr)
-
- return rec_nos
-
-
- def update(self, name, fields, searchData, updates, filter = None, useRegExp = False):
- """Update record(s) in table, return number of records updated.
-
- Arguments:
- name - physical file name, including path, that holds
- table.
- fields - list containing names of fields to search on. If
- any of the items in this list is 'recno', then the
- table will be searched by the recno field only and
- will update, at most, one record, since recno is
- the system generated primary key.
- searchData - list containing actual data to search on. Each
- item in list corresponds to item in the 'fields'
- list.
- updates - list, dictionary, or object containing actual data
- to put into table field. If it is a list and
- 'filter' list is empty or equal to None, then
- updates list must have a value for each field in
- table record.
- filter - only used if 'updates' is a list. This is a
- list containing names of fields to update. Each
- item in list corresponds to item in the 'updates'
- list. If 'filter' list is empty or equal to None,
- and 'updates' is a list, then 'updates' list must
- have an item for each field in table record,
- excepting the recno field.
- useRegExp - if true, match string fields using regular
- expressions, else match string fields using
- strict equality (i.e. '=='). Defaults to true.
-
- Returns integer specifying number of records that were updated.
-
- Example:
- db.update('plane.tbl',['country','speed'],['USA','>400'],
- [1230],['range'])
-
- This will search for any plane from the USA with a speed
- greater than 400mph and update it's range to 1230 miles.
- """
- patterns = list(searchData)
- fptr = self._openTable(name, 'r+')
- self._updateHeaderVars(fptr)
- if filter:
- if isinstance(updates, list):
- pass
- elif isinstance(updates, dict):
- raise KBError('Cannot specify filter when updates is a ' + 'dictionary.')
- else:
- raise KBError('Cannot specify filter when updates is an ' + 'object.')
- elif isinstance(updates, list):
- filter = self.field_names[1:]
-
- if isinstance(updates, list):
- pass
- elif isinstance(updates, dict):
- filter = _[1]
- updates = [ updates[i] for i in filter ]
- else:
- filter = _[3]
- updates = _[4]
-
- try:
- self._validateMatchCriteria(fields, patterns)
- self._validateUpdateCriteria(updates, filter)
- except KBError:
- []
- []
- []
- fptr.close()
- raise
- except:
- []
-
- match_list = self._getMatches(fptr, fields, patterns, useRegExp)
- filter_updates = []([], [ self._encodeString(str(u)) for u in updates ])
- updated = 0
- for line, fpos in match_list:
- new_record = line.strip().split('|')
- for field, update in filter_updates:
- new_record[self.field_names.index(field)] = update
-
- new_line = '|'.join(new_record)
- self._deleteRecord(fptr, fpos, line)
- updated += 1
-
- self._closeTable(fptr)
- return updated
-
-
- def delete(self, name, fields, searchData, useRegExp = False):
- """Delete record(s) from table, return number of records deleted.
-
- Arguments:
- name - physical file name, including path, that holds
- table.
- fields - list containing names of fields to search on. if
- any of the items in this list is 'recno', then the
- table will be searched by the recno field only and
- will delete, at most, one record, since recno is
- the system generated primary key.
- searchData - list containing actual data to search on. Each
- item in list corresponds to item in the 'fields'
- list.
- useRegExp - if true, match string fields using regular
- expressions, else match string fields using
- strict equality (i.e. '=='). Defaults to true.
-
- Returns integer specifying number of records that were deleted.
-
- Example:
- db.delete('plane.tbl',['country','speed'],['USA','>400'])
-
- This will search for any plane from the USA with a speed
- greater than 400mph and delete it.
- """
- patterns = list(searchData)
- fptr = self._openTable(name, 'r+')
- self._updateHeaderVars(fptr)
-
- try:
- self._validateMatchCriteria(fields, patterns)
- except KBError:
- fptr.close()
- raise
-
- match_list = self._getMatches(fptr, fields, patterns, useRegExp)
- deleted = 0
- for line, fpos in match_list:
- self._deleteRecord(fptr, fpos, line)
- self._incrDeleteCounter(fptr)
- deleted += 1
-
- self._closeTable(fptr)
- return deleted
-
-
- def select(self, name, fields, searchData, filter = None, useRegExp = False, sortFields = [], sortDesc = [], returnType = 'list', rptSettings = [
- 0,
- False]):
- """Select record(s) from table, return list of records selected.
-
- Arguments:
- name - physical file name, including path, that holds
- table.
- fields - list containing names of fields to search on.
- If any of the items in this list is 'recno',
- then the table will be searched by the recno
- field only and will select, at most, one record,
- since recno is the system generated primary key.
- searchData - list containing actual data to search on. Each
- item in list corresponds to item in the
- 'fields' list.
- filter - list containing names of fields to include for
- selected records. If 'filter' list is empty or
- equal to None, then all fields will be included
- in result set.
- useRegExp - if true, match string fields using regular
- expressions, else match string fields using
- strict equality (i.e. '=='). Defaults to False.
- sortFields - list of fieldnames to sort on. Each must be a
- valid field name, and, if filter list is not
- empty, the same fieldname must be in the filter
- list. Result set will be sorted in the same
- order as fields appear in sortFields in
- ascending order unless the same field name also
- appears in sortDesc, then they will be sorted in
- descending order.
- sortDesc - list of fieldnames that you want to sort result
- set by in descending order. Each field name
- must also be in sortFields.
- returnType - a string specifying the type of the items in the
- returned list. Can be 'list' (items are lists
- of values), 'dict' (items are dictionaries with
- keys = field names and values = matching
- values), 'object' (items = instances of the
- generic Record class) or 'report' (result set
- is formatted as a table with a header, suitable
- for printing). Defaults to list.
- rptSettings - a list with two elements. This is only used if
- returnType is 'report'. The first element
- specifies the number of records to print on each
- page. The default is 0, which means do not do
- any page breaks. The second element is a
- boolean specifying whether to print a row
- separator (a line of dashes) between each
- record. The default is False.
-
- Returns list of records matching selection criteria.
-
- Example:
- db.select('plane.tbl',['country','speed'],['USA','>400'])
-
- This will search for any plane from the USA with a speed
- greater than 400mph and return it.
- """
- if returnType not in ('list', 'dict', 'object', 'report'):
- raise KBError('Invalid return type: %s' % returnType)
-
- if type(rptSettings[0]) != int:
- raise KBError('Invalid report setting: %s' % rptSettings[0])
-
- if type(rptSettings[1]) != bool:
- raise KBError('Invalid report setting: %s' % rptSettings[1])
-
- patterns = list(searchData)
- fptr = self._openTable(name, 'r')
- self._updateHeaderVars(fptr)
-
- try:
- self._validateMatchCriteria(fields, patterns)
- if filter:
- self._validateFilter(filter)
- else:
- filter = self.field_names
- except KBError:
- fptr.close()
- raise
-
- for sf in sortFields:
- if sf not in filter:
- continue
- _[1][sf]
-
- for sf in sortDesc:
- if sf not in sortFields:
- continue
- _[2][sf]
-
- match_list = self._getMatches(fptr, fields, patterns, useRegExp)
- result_set = []
- filterIndeces = [ self.field_names.index(x) for x in filter ]
- for record, fpos in match_list:
- result_rec = []
- fields = record.split('|')
- for None in filterIndeces:
- i = None
-
- result_set.append(result_rec)
-
- self._closeTable(fptr)
- if returnType == 'object':
- return [ Record(filter, rec) for rec in result_set ]
- elif returnType == 'dict':
- return [ dict(zip(filter, rec)) for rec in result_set ]
- elif returnType == 'report':
- numRecsPerPage = rptSettings[0]
- rowSeparator = rptSettings[1]
- delim = ' | '
- columns = apply(zip, [
- filter] + result_set)
- maxWidths = [ []([ len(str(item)) for item in column ]) for column in columns ]
- rowDashes = '-' * (sum(maxWidths) + len(delim) * (len(maxWidths) - 1))
- justifyDict = {
- str: str.ljust,
- int: str.rjust,
- float: str.rjust,
- bool: str.ljust,
- datetime.date: str.ljust,
- datetime.datetime: str.ljust }
- headerLine = []([ justifyDict[fieldType](item, width) for item, width, fieldType in zip(filter, maxWidths, self.field_types) ])
- output = cStringIO.StringIO()
- recsOnPageCount = 0
- for row in result_set:
- print >>[], []([ justifyDict[fieldType](str(item), width) for item, width, fieldType in zip(row, maxWidths, self.field_types) ]),
- print >>delim.join
- recsOnPageCount += 1
- if numRecsPerPage > 0 and recsOnPageCount == numRecsPerPage:
- print >>output, '\x0c',
- recsOnPageCount = 0
- continue
- [] if rowSeparator else [] if recsOnPageCount == 0 else _[6]
-
- return output.getvalue()
- else:
- return result_set
-
-
- def pack(self, name):
- '''Remove blank records from table and return total removed.
-
- Keyword Arguments:
- name - physical file name, including path, that holds table.
-
- Returns number of blank lines removed from table.
- '''
- fptr = self._openTable(name, 'r')
- lines = fptr.readlines()
- self._closeTable(fptr)
- header_rec = lines[0].split('|')
- header_rec[1] = '000000'
- lines[0] = '|'.join(header_rec)
- fptr = self._openTable(name, 'w')
- lines_deleted = 0
- for line in lines:
- line = line.rstrip()
- if line == '':
- lines_deleted += 1
- continue
-
-
- try:
- fptr.write(line + '\n')
- continue
- raise KBError('Could not write record in: ' + name)
- continue
-
-
- self._closeTable(fptr)
- return lines_deleted
-
-
- def validate(self, name):
- '''Validate all records have field values of proper data type.
-
- Keyword Arguments:
- name - physical file name, including path, that holds table.
-
- Returns list of records that have invalid data.
- '''
- fptr = self._openTable(name, 'r')
- self._updateHeaderVars(fptr)
- invalid_list = []
- for line in fptr:
- line = line[:-1].strip()
- if line == '':
- continue
-
- record = line.split('|')
- if self.last_recno < int(record[0]):
- invalid_list.append([
- record[0],
- 'recno',
- record[0]])
-
- for i, item in enumerate(record):
- if item == '':
- continue
-
-
- try:
- if self.convert_types_functions[i](item):
- pass
- continue
- invalid_list.append([
- record[0],
- self.field_names[i],
- item])
- continue
-
-
-
- self._closeTable(fptr)
- return invalid_list
-
-
- def drop(self, name):
- '''Delete physical file containing table and return True.
-
- Arguments:
- name - physical filename, including path, that holds table.
-
- Returns True if no exceptions are raised.
- '''
- os.remove(name)
- return True
-
-
- def getFieldNames(self, name):
- '''Return list of field names for specified table name
-
- Arguments:
- name - physical file name, including path, that holds table.
-
- Returns list of field names for table.
- '''
- fptr = self._openTable(name, 'r')
- self._updateHeaderVars(fptr)
- self._closeTable(fptr)
- return self.field_names
-
-
- def getFieldTypes(self, name):
- '''Return list of field types for specified table name
-
- Arguments:
- name - physical file name, including path, that holds table.
-
- Returns list of field types for table.
- '''
- fptr = self._openTable(name, 'r')
- self._updateHeaderVars(fptr)
- self._closeTable(fptr)
- return self.field_types
-
-
- def len(self, name):
- '''Return total number of non-deleted records in specified table
-
- Arguments:
- name - physical file name, including path, that holds table.
-
- Returns total number of records in table.
- '''
- rec_count = 0
- fptr = self._openTable(name, 'r')
- line = fptr.readline()
- line = fptr.readline()
- while line:
- line = line[0:-1]
- if line.strip() != '':
- rec_count += 1
-
- line = fptr.readline()
- self._closeTable(fptr)
- return rec_count
-
-
- def _strToBool(self, boolString):
- if boolString == 'True':
- return True
- elif boolString == 'False':
- return False
- else:
- raise KBError('Invalid value for boolean: %s' % boolString)
-
-
- def _strToDate(self, dateString):
- return datetime.date(*map(int, dateString.split('-')))
-
-
- def _strToDateTime(self, dateTimeString):
- tempDateTime = dateTimeString.split('.')
- if len(tempDateTime) > 1:
- microsec = int(tempDateTime[1])
- else:
- microsec = 0
- (tempDate, tempTime) = tempDateTime[0].split(' ')
- (y, m, d) = tempDate.split('-')
- (h, min, sec) = tempTime.split(':')
- return datetime.datetime(int(y), int(m), int(d), int(h), int(min), int(sec), microsec)
-
-
- def _encodeString(self, s):
- '''Encode a string.
-
- Translates problem characters like
- , \r, and \x1a to benign
- character strings.
-
- Keyword Arguments:
- s - string to encode.
-
- Returns encoded string.
- '''
- if self.encodeRegExp.search(s):
- s = s.replace('\n', '&linefeed;')
- s = s.replace('\r', '&carriage_return;')
- s = s.replace('\x1a', '&substitute;')
- s = s.replace('|', '&pipe;')
-
- return s
-
-
- def _unencodeString(self, s):
- '''Unencode a string.
-
- Translates encoded character strings back to special characters
- like
- , \r, \x1a.
-
- Keyword Arguments:
- s - string to unencode.
-
- Returns unencoded string.
- '''
- if self.unencodeRegExp.search(s):
- s = s.replace('&linefeed;', '\n')
- s = s.replace('&carriage_return;', '\r')
- s = s.replace('&substitute;', '\x1a')
- s = s.replace('&pipe;', '|')
-
- return s
-
-
- def _updateHeaderVars(self, fptr):
- fptr.seek(0)
- line = fptr.readline()
- line = line[0:-1]
- header_rec = line.split('|')
- self.last_recno = int(header_rec[0])
- self.del_counter = int(header_rec[1])
- header_fields = header_rec[2:]
- self.field_names = [ item.split(':')[0] for item in header_fields ]
- self.field_types = [ self.strToTypes[x.split(':')[1]] for x in header_fields ]
- convTypes = {
- int: int,
- float: float,
- bool: bool,
- str: self._unencodeString,
- datetime.date: self._strToDate,
- datetime.datetime: self._strToDateTime }
- self.convert_types_functions = [ convTypes[f] for f in self.field_types ]
-
-
- def _validateMatchCriteria(self, fields, patterns):
- '''Run various checks against list of fields and patterns to be
- used as search criteria. This method is called from all public
- methods that search the database.
- '''
- if len(fields) == 0:
- raise KBError('Length of fields list must be greater ' + 'than zero.')
-
- if len(fields) != len(patterns):
- raise KBError('Length of fields list and patterns list ' + 'not the same.')
-
- for field, pattern in zip(fields, patterns):
- if field not in self.field_names:
- raise KBError('Invalid field name in fields list: %s' % field)
-
- if field == 'recno':
- if len(fields) > 1:
- raise KBError('If selecting by recno, no other ' + 'selection criteria is allowed')
-
- if pattern != '*':
- if not isinstance(pattern, (tuple, list)):
- pattern = [
- pattern]
-
- for x in pattern:
- if not isinstance(x, int):
- raise KBError('Recno argument %s has type %s, expected an integer' % (x, type(x)))
- continue
-
- continue
-
- if self.field_types[self.field_names.index(field)] in [
- int,
- float,
- datetime.date,
- datetime.datetime]:
- r = re.search('[\\s]*[\\+-]?\\d', pattern)
- if not self.cmpFuncs.has_key(pattern[:r.start()]):
- raise KBError('Invalid comparison syntax: %s' % pattern[:r.start()])
-
- self.cmpFuncs.has_key(pattern[:r.start()])
-
-
-
- def _convertInput(self, values):
- '''If values is a dictionary or an object, we are going to convert
- it into a list. That way, we can use the same validation and
- updating routines regardless of whether the user passed in a
- dictionary, an object, or a list.
- '''
- if isinstance(values, list):
- record = list(values)
- elif isinstance(values, dict):
- record = [ values.get(k, '') for k in self.field_names[1:] ]
- else:
- record = [ getattr(values, a, '') for a in self.field_names[1:] ]
- new_rec = []
- for r in record:
- if r == None:
- new_rec.append('')
- continue
- []
- new_rec.append(r)
-
- return new_rec
-
-
- def _validateUpdateCriteria(self, updates, filter):
- '''Run various checks against list of updates and fields to be
- used as update criteria. This method is called from all public
- methods that update the database.
- '''
- if len(updates) == 0:
- raise KBError('Length of updates list must be greater ' + 'than zero.')
-
- if len(updates) != len(filter):
- raise KBError('Length of updates list and filter list ' + 'not the same.')
-
- if 'recno' in filter:
- raise KBError("Cannot update value of 'recno' field.")
-
- self._validateFilter(filter)
- for update, field_name in zip(updates, filter):
- if update in ('', None):
- continue
- if type(update) != self.field_types[self.field_names.index(field_name)]:
- raise KBError('Invalid update value for %s' % field_name)
- continue
-
-
-
- def _validateFilter(self, filter):
- for field in filter:
- if field not in self.field_names:
- raise KBError('Invalid field name: %s' % field)
- continue
-
-
-
- def _getMatches(self, fptr, fields, patterns, useRegExp):
- match_list = []
- if 'recno' in fields:
- return self._getMatchByRecno(fptr, patterns)
- else:
- new_patterns = []
- fieldNrs = [ self.field_names.index(x) for x in fields ]
- for fieldPos, pattern in zip(fieldNrs, patterns):
- if self.field_types[fieldPos] == str:
- if useRegExp:
- new_patterns.append(re.compile(pattern))
- else:
- new_patterns.append(pattern)
- useRegExp
- if self.field_types[fieldPos] == bool:
- new_patterns.append(str(bool(pattern)))
- continue
- []
- r = re.search('[\\s]*[\\+-]?\\d', pattern)
- if self.field_types[fieldPos] == int:
- patternValue = int(pattern[r.start():])
- elif self.field_types[fieldPos] == float:
- patternValue = float(pattern[r.start():])
- else:
- patternValue = pattern[r.start():]
- new_patterns.append([
- self.cmpFuncs[pattern[:r.start()]],
- patternValue])
-
- fieldPos_new_patterns = zip(fieldNrs, new_patterns)
- maxfield = max(fieldNrs) + 1
- fpos = fptr.tell()
- line = fptr.readline()
- while line:
- line = line[:-1].strip()
-
- try:
- if line == '':
- raise 'No Match'
-
- record = line.split('|', maxfield)
- for fieldPos, pattern in fieldPos_new_patterns:
- if self.field_types[fieldPos] == str:
-
- try:
- if useRegExp:
- if not pattern.search(self._unencodeString(record[fieldPos])):
- raise 'No Match'
-
- elif record[fieldPos] != pattern:
- raise 'No Match'
- except Exception:
- raise KBError('Invalid match expression for %s' % self.field_names[fieldPos])
- except:
- None<EXCEPTION MATCH>Exception
-
-
- None<EXCEPTION MATCH>Exception
- if self.field_types[fieldPos] == bool:
- if record[fieldPos] != pattern:
- raise 'No Match'
-
- record[fieldPos] != pattern
- if record[fieldPos] == '':
- tableValue = None
- elif self.field_types[fieldPos] == int:
- tableValue = int(record[fieldPos])
- elif self.field_types[fieldPos] == float:
- tableValue = float(record[fieldPos])
- elif self.field_types[fieldPos] in (datetime.date, datetime.datetime):
- tableValue = record[fieldPos]
- else:
- raise KBError('Invalid field type for %s' % self.field_names[fieldPos])
- if not pattern[0](tableValue, pattern[1]):
- raise 'No Match'
- continue
- except 'No Match':
- pass
-
- match_list.append([
- line,
- fpos])
- fpos = fptr.tell()
- line = fptr.readline()
- return match_list
-
-
- def _getMatchByRecno(self, fptr, recnos):
- """Search by recnos. recnos is a list, containing '*', an integer, or
- a list or tuple of integers"""
- fpos = fptr.tell()
- line = fptr.readline()
- if recnos == [
- '*']:
- while line:
- line = line[:-1]
- if line.strip():
- yield [
- line,
- fpos]
-
- fpos = fptr.tell()
- line = fptr.readline()
- elif isinstance(recnos[0], (tuple, list)):
- recnos = list(recnos[0])
-
- while line:
- line = line[0:-1]
- if line.strip():
- record = line.split('|')
- if int(record[0]) in recnos:
- yield [
- line,
- fpos]
- recnos.remove(int(record[0]))
- if not recnos:
- break
-
-
-
- fpos = fptr.tell()
- line = fptr.readline()
-
-
- def _incrRecnoCounter(self, fptr):
- last_pos = fptr.tell()
- fptr.seek(0)
- line = fptr.readline()
- header_rec = line[0:-1].split('|')
- self.last_recno += 1
- header_rec[0] = '%06d' % self.last_recno
- self._writeRecord(fptr, 0, '|'.join(header_rec))
- fptr.seek(last_pos)
- return self.last_recno
-
-
- def _incrDeleteCounter(self, fptr):
- last_pos = fptr.tell()
- fptr.seek(0)
- line = fptr.readline()
- header_rec = line[0:-1].split('|')
- self.del_counter += 1
- header_rec[1] = '%06d' % self.del_counter
- self._writeRecord(fptr, 0, '|'.join(header_rec))
- fptr.seek(last_pos)
-
-
- def _deleteRecord(self, fptr, pos, record):
- fptr.seek(pos)
- self._writeRecord(fptr, pos, ' ' * len(record))
-
-
- def _writeRecord(self, fptr, pos, record):
-
- try:
- if pos == 'end':
- fptr.seek(0, 2)
- fptr.write(record + '\n')
- else:
- fptr.seek(pos)
- fptr.write(record)
- except:
- raise KBError('Could not write record to: ' + fptr.name)
-
-
-
- def _openTable(self, name, access):
-
- try:
- fptr = open(name, access)
- except:
- raise KBError('Could not open table: ' + name)
-
- return fptr
-
-
- def _closeTable(self, fptr):
-
- try:
- fptr.close()
- except:
- raise KBError('Could not close table: ' + fptr.name)
-
-
-
-
- class Record(object):
- '''Generic class for record objects.
-
- Public Methods:
- __init__ - Create an instance of Record.
- '''
-
- def __init__(self, names, values):
- self.__dict__ = dict(zip(names, values))
-
-
-
- class KBError(Exception):
- '''Exception class for Database Management System.
-
- Public Methods:
- __init__ - Create an instance of exception.
- '''
-
- def __init__(self, value):
- self.value = value
-
-
- def __str__(self):
- return `self.value`
-
-
- def __repr__(self):
- format = 'KBError("%s")'
- return format % self.value
-
-
-