/* Rangarajan Krishnamoorthy, 15/8/2019 Using Berkeley DB with Sicstus Prolog 4.5.1 (64 bit, Windows 10) */ ?- use_module(library(file_systems)). ?- use_module(library(bdb)). /* Change to the working directory */ ?- current_directory(_CurDir, 'G:/Prolog Projects/BerkeleyDB'). /* Create a new database with and populate it with the facts stored in . The terms stored in the database will conform to the specification . The database is finally closed. */ create_db(DbName, InFile, PredSpec) :- db_open(DbName, update, PredSpec, DbRef), open(InFile, read, Strm), catch(read_update_db(Strm, DbRef), _Error, true), db_close(DbRef), close(Strm). read_update_db(InStrm, DbRef) :- read(InStrm, Fact), db_store(DbRef, Fact, _), read_update_db(InStrm, DbRef). /* ?- create_db(remediesdb, 'G:/Prolog Projects/BerkeleyDB/remedies.pl', [abbrev(+,-), abbrev(-,+), abbrev(-,-), group(+,-), miasm(+,-), complementary(+,-)]). */ /* To update an existing database, we open it in 'update' mode and supply the same specification used at the time of creating the database. is the new term we want to insert. */ update_db(DbName, PredSpec, Fact2Insert) :- db_open(DbName, update, PredSpec, DbRef), db_store(DbRef, Fact2Insert, _), db_close(DbRef). /* ?- update_db(remediesdb, [abbrev(+,-), abbrev(-,+), abbrev(-,-), group(+,-), miasm(+,-), complementary(+,-)], abbrev('acon.', 'aconitum napellus')). */ /* Open the DB for reading. Save the DB reference for subsequent use. */ open_db(DbName) :- db_open(DbName, read, _PredSpec, DbRef), assert(dbinfo(DbName, DbRef)). /* Close the database */ close_db(DbName) :- dbinfo(DbName, DbRef), db_close(DbRef), retract(dbinfo(DbName, DbRef)). /* Retrieve a from the DB. Database must be open for this to work. */ get_fact_db(DbName, Fact) :- dbinfo(DbName, DbRef), db_fetch(DbRef, Fact, _TermRef). /* Iterate over all the terms in the DB and apply an action on them. */ traverse_db(DbName, Action) :- dbinfo(DbName, DbRef), db_make_iterator(DbRef, Iter), iterate_over_db1(Iter, Action). iterate_over_db1(Iter, Action) :- db_iterator_next(Iter, Term, _TermRef), call(Action, Term), iterate_over_db1(Iter, Action). iterate_over_db1(Iter, _Action):- db_iterator_done(Iter). /* Apply this on each Term in the database */ print_term(Term) :- write(Term), nl.