
/* testdb.q: simple example illustrating the use of the gdbm interface to
   store arbitrary (printable) Q values in a string-indexed database.
   05-05-2003 AG */

import gdbm;

/* A sample database file to be used with the functions below. We open it for
   both reading and writing, and create it if necessary. */

def DBF = gdbm_open "testdb" 512 GDBM_WRCREAT 0666;

/* Store an arbitrary (printable) Q object in the database under a given key
   (a string). An existing entry under the same key will be replaced. */

store DBF:GdbmFile KEY:String VAL
			= gdbm_store DBF (bytestr KEY) (bytestr (str VAL))
			  GDBM_REPLACE;

/* Fetch the value of a key in the database. */

fetch DBF:GdbmFile KEY:String
			= val (bstr (gdbm_fetch DBF (bytestr KEY)))
			    if gdbm_exists DBF (bytestr KEY);

/* Delete the given key. */

delete DBF:GdbmFile KEY:String
			= gdbm_delete DBF (bytestr KEY)
			    if gdbm_exists DBF (bytestr KEY);

/* List the (KEY,VAL) pairs in the database. */

list DBF:GdbmFile	= zip (map bstr KEYS) (map (val.bstr) VALS)
			    where KEYS = while isbytestr
			      (gdbm_nextkey DBF) (gdbm_firstkey DBF),
			      VALS = map (gdbm_fetch DBF) KEYS;
