#
# Copyright (C) 2005-2008 Christoph Rupp (chris@crupp.de).
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or 
# (at your option) any later version.
#
# See file COPYING.GPL2 and COPYING.GPL3 for License information.
#

#
# a simple demo which creates a database, inserts some values, looks
# them up and deletes them. 
#

# set the library path, otherwise hamsterdb.so/.dll is not found
# these lines are specific for the hamsterdb-python distribution; you do
# not need to add them, if your hamsterdb-python library is properly
# installed
import os
import sys
import distutils.util
p    = distutils.util.get_platform()
ps   = ".%s-%s" % (p, sys.version[0:3])
sys.path.insert(0, os.path.join('build', 'lib'+ps))
sys.path.insert(1, os.path.join('..', 'build', 'lib'+ps))
import hamsterdb

def run_demo():
    LOOP=10
    db=hamsterdb.db()

    # first, create a new database file
    db.create("test.db")

    # now we can insert, delete or lookup values in the database
    #
    # for our test program, we just insert a few values, then look them
    # up, then delete them, then look them up again (which will fail).
    for i in range(0, LOOP):
        db.insert("%d"%i, "%d"%i)

    # now lookup the values
    for i in range(0, LOOP):
        v=db.find("%d"%i)
        assert v == "%d"%i

    # close the database, then re-open it (just to demonstrate how to open
    # a database file)
    db.close()
    db.open("test.db")

    # now erase all values
    for i in range(0, LOOP):
        db.erase("%d"%i)

    # once more we try to find all values... every db.find() call must now
    # fail with HAM_KEY_NOT_FOUND
    for i in range(0, LOOP):
        try:
            v=db.find("%d"%i)
            assert 0 == 1 # will never reach this line
        except hamsterdb.error, (errno, message):
            assert errno == hamsterdb.HAM_KEY_NOT_FOUND

    # we're done! No need to close the database handle, it's closed 
    # automatically
    print "success!"
    return 0

try:
    exit(run_demo())
except hamsterdb.error, (errno, message):
    print "unexpected exception", errno, "-", message
    exit(-1)
