Shelve Database Engine

User Guide | Documentation | View Source
>>> from ShelveDB import ShelveDB

# Startup shdb interface, creates filename given
>>> DB = ShelveDB('mydb')    

# True if whole database is empty
>>> DB.is_empty()
True

# Creating tables
# takes a name and type pair either by strings
>>> DB.create('words','name=str','usage=int')

# or by keywords, any python types will work here
>>> DB.create('colors',red=int(),green=int(),blue=int())

# Inserting only works by column name, value pairs
# returns key id
# columns left out will be blank
>>> DB.insert('words', name='hat', usage=23)
0 
>>> DB.insert('words', name='cat', usage=2)
1
>>> DB.insert('words', name='chat')
2

# True if table is empty
>>> DB.is_empty('words')
False

# Lenth of database, two ways
>>> len(DB), DB.len()
2 2
# length of table
>>> DB.len('words')
3

# Selection,
# Returns list of ids
# supports:
# exact matching
>>> DB.select('words',name='hat')
[0]
# startswith,endswith identifiers '%'
>>> DB.select('words',name='%hat')
[0, 2]
# regular expressions searching through compiled patterns
>>> DB.select('words',name=re.compile('[hc]+at'))
[0, 1, 2]

# Fetching a selection
# returns generator for iterating
>>> words = DB.select('words', fetch=True)
# fetch elements as dictionaries
>>> words.next().dict()
{'usage': 23, 'name': 'chatty', 'key': 0}
# fetch elements as lists
>>> words.next().list()
[2, 'cat', 1]
# fetch elements as tuples
>>> words.next().tuple()
(2, 'cat', 1)

# fetch iteratively
>>> for row in DB.select('words', fetch=True):
...    print 'The word %s has been used %d times'%(row['name'],row['usage'])
The word chatty has been used 23 times
The word cat has been used 2 times
The word chat has been used 0 times

# Updating
# fetch a record
>>> Record = DB.fetch('words',0) 
# mutate record
>>> Record['name'] = 'chatty'
# Update record satisfying the kwargs selection
# kwargs are the same format as select    
>>> DB.update('words',Record,key=0)

# Dumps data structure of database
# to outfile (default stdout)
>>> DB.dump()
Database mydb, 2 tables
   Table colors, 3 columns
      blue : 
      green : 
      red : 
   Table words, 2 columns
      usage : 
      name : 
DATA = {
   'mydb' :
      'colors' : {
         'blue' = []
         'green' = []
         'red' = []
         'key' = []
      },
      'words' : {
         'usage' = [23, 2, 0]
         'name' = ['chatty', 'cat', 'chat',]
         'key' = [0, 1, 2]
      },
}
# Saves all information to disk
>>> DB.sync()
# Closes database file, also performed atexit
>>> DB.close()