# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
from java.lang import String
from java.io import File

from com.sleepycat.je import Environment
from com.sleepycat.je import EnvironmentConfig
from com.sleepycat.persist import EntityStore
from com.sleepycat.persist import PrimaryIndex
from com.sleepycat.persist import StoreConfig

import DataO

def dump(pk, key):
    print('Key=%s' % (key))
    if pk.contains(key):
        o = pk.get(key)
        print(o)
    else:
        print('Not found')

NREC = 1000

# open database
envcfg = EnvironmentConfig()
envcfg.setAllowCreateVoid(True)
env = Environment(File("data/"), envcfg)
stcfg = StoreConfig()
stcfg.setAllowCreate(True)
est = EntityStore(env, "testdb", stcfg)
pk = est.getPrimaryIndex(String, DataO);
# put data
for i in range(NREC):
    o = DataO('Key#' + str(1000 + i + 1), i + 1, i + 1.0, 'This is value %d' % (i + 1))
    pk.put(o)
#
key = "Key#" + str(1077)
# get
dump(pk, key)
# delete
pk.delete(key)
# get non existing
dump(pk, key)
#
key = "Key#" + str(1088)
# update and get
dump(pk, key)
o = pk.get(key)
o.iv = o.iv + 1
o.xv = o.xv + 0.1
o.sv = o.sv + ' updated'
pk.put(o)
dump(pk, key)
# list all
c = pk.entities()
n = 0
for o in c.iterator():
    if not o.key.startswith('Key#'):
        print('Unexpected key: ' + o.id)
    if o.iv < 1 or NREC < o.iv:
        print('Unexpected value: ' + d)
    n = n + 1
c.close()
print(n)
# list keys where "Key#1075" <= key < "Key#1085"
c2 = pk.entities('Key#1075', True, 'Key#1085', False)
n2 = 0
for o in c2.iterator():
    n2 = n2 + 1
c2.close()
print(n2)
# close database
est.close()
env.close()

