Creating a database |
from buzhug import Base
db = Base(path)
db.create((name1,type1[,default1])[,(name2,type2[,default2]),...][,mode=cr_mode])
type can be str, unicode, int, float, bool, date, datetime, another instance of Base
cr_mode can be "override" or "open". If a base already exists in the specified path, on override mode it is replaced with the new definition, if mode is "open" this base is opened
For a thread-safe version, create an instance of TS_Base instead of Base
from buzhug import TS_Base
db = TS_Base(path)
|
Opening an existing database |
db = Base(path).open()
|
Closing a database |
db.close()
|
Inserting a record in a database |
by keyword : rec_id = db.insert(name1=val1[,name2=val2,...])
rec_id is an integer that identifies the record
by list : db.insert(val1,val2,...)
as strings :
db.insert_as_strings(name1=string1[,name2=string2,...])
db.insert_as_strings(string1,string2,...)
For date, datetime and unicode, first specify the string format by
db.set_string_format(unicode,encoding)
db.set_string_format(date,strftime_format)
db.set_string_format(datetime,strftime_format)
|
Record structure |
Records are Python objects with attributes of the same name as the fields
The database engine automatically adds two attributes :
__id__ , a unique integer for each record
__version__ set to 0 when a record is first inserted, then incremented by 1 each time the record is updated ; this field is intended to be used to detect update conflicts
|
Selecting a record |
direct access by identifier
record = db[rec_id]
list comprehension, generator expression
record_set = [ record for record in db if condition ]
for record in (record for record in db if condition):
(...do anything with record...)
select() function
result_set = db.select(field_list,n1=v1,n2=v2...)
result_set = db.select(field_list,n1=[min1,max1],...)
result_set = db.select(field_list,predicate_str,kw_arguments)
If the records are selected for update, use select_for_update() instead of select()
Sorting the result :
results = result_set.sort_by(" + field1 - field2...")
|
Updating a record |
record.update(name1=newval1[,name2=newval2,...])
db.update(record,name1=newval1[,name2=newval2,...])
db.update(record_list,name1=newval1[,name2=newval2,...]) (list of records)
|
Deleting records |
db.delete(record) # delete one record
db.delete(records) # delete a list of records
del db[record_id] # delete by record id
|
Cleaning up the base |
db.cleanup() physically removes the deleted items from disk
|
External references |
A reference to a base can be used as a type in another base
base1 = Base('base1').create((n1,t1),(n2,t2))
base2 = Base('base2').create((n3,t3),(n4,base1))
Instances of base2 have attributes n4.n1 and n4.n2
|
Modifying the database structure |
Adding a new field : db.add_field(field_name,field_type[,after[,default]])
Removing a field : db.drop_field(field_name)
|