TextDB.py

Description
TextDB.py is a single file that contains a class for manipulating loosely structured text records. The records are not truly relational, as records from the same source may have different attributes.
The on-disk structure is a simple text file of attribute/value pairs. Upon construction, the source file is parsed and the records are stored as a list of dictionaries, self.Records
See below for an example of the file format.



Version
This document covers version 1.0.0 July 19,2000.


Author and copyright
Written by Nathan Denny. This code is in the public domain. No warranty on correctness.


Example
dbtest.txt
Name: Julius Caesar
Occupation: Emperor of Rome
Phone: 555-1212
Phone: 555-9906
AreaCode: 314
 
Name: Alexander The Great
Occupation: Conqueror
Phone: 555-1232
AreaCode: 618
 
Name: Vlad the Impaler
Occupation: Despot
import TextDB
DB=TextDB.Textbase('dbtest.txt')
#-- Chooses both Julius and Alexander
qset=DB.Select({'Phone':'555*'})
#-- Deletes Vlad
qset=DB.Delete({'Occupation':'Despot'})
#-- Adds Ghengis
new_num=DB.Insert({'Name':'Ghengis Khan','Occupation':'Conqueror'})
#-- Commits changes back to disk
DB.Write()



TextDB.Textbase

__init__(self,source_file_name)

Opens and parses the file with name, source_file_name. All records are stored in memory in the list, self.Records
Insert(self,records)
records may either be a single dictionary or a list of dictionaries. In the former case the self.Records list is updated with a reference to the given dictionary. In the latter case, self.Records is updated with each dictionary in the list.
The return value is a single integer if a single record was inserted, or a list of integers if a list of records was inserted. The returned integers are the index in the self.Records list.
Select(self,query)
Returns a list of record references that match the given query.
Queries are specified as a set of dictionaries of the form:
{'Attribute':'pattern'}
Attribute names are case sensitive. pattern is a text pattern using filename-style wildcards, ie. * and ?
pattern can also be a list of patterns. ie. {'Name':['John*','David*']} in which case records that have a Name headed with John or David are selected.
The dictionaries can themselves be put into a list. The resulting set is a union of the results produced by each dictionary in the list. ie. [{'Name':'John Smith'},{'Phone':'314*'}]
will result in a list of records that have a Name of John Smith or a Phone attribute headed with 314.
Delete(self,query)
Returns a list of references that satisfy the query. (See the Select method.) The returned references have been deleted from self.Records
Write(self)
Writes the records in self.Records to the file named for construction.
Commit(self)
An alias for self.Write( )