Using the persdb library

Author(s): The Ciao Development Team.

Through the following examples we will try to illustrate the two mains ways of declaring and using persistent predicates: statically (the preferred method) and dynamically (necessary when the new persistent predicates have to be defined at run-time). The final example is a small application implementing a simple persistent queue.

An example of persistent predicates (static version)

:- module(example_static,[main/0],[persdb,iso]).

%% Declare the directory associated to the key "db" where the
%% persistence sets of the persistent predicates are stored:
persistent_dir(db,'./').

%% Declare a persistent predicate:
:- persistent(bar/1, db).

%% Read a term, storing it in a new fact of the persistent predicate
%% and list all the current facts of that predicate
main :-
 	read(X),
 	assertz_fact(bar(X)),
 	findall(Y,bar(Y),L),
 	write(L).

erase_one :-
	retract_fact(bar(_)).
erase_all :-
	retractall_fact(bar(_)).

An example of persistent predicates (dynamic version)

:- module(example_dynamic,[main/1],[persdb,iso]).

main([X]):-
	% Declare the directory associated to the key "db" 
	asserta_fact(persistent_dir(db,'./')),
	% Declare the predicate bar/1 as dynamic (and data) at run-time  
	data(bar/1),
	% Declare the predicate bar/1 as persistent at run-time  
	make_persistent(bar/1, db),
	assertz_fact(bar(X)),
	findall(Y, bar(Y), L),
	write(L).    

A simple application / a persistent queue

:- module(queue, [main/0],[persdb,iso]).

:- use_module(library(streams)).
:- use_module(library(read)).
:- use_module(library(write)).
:- use_module(library(aggregates)).

persistent_dir(queue_dir,'./pers').

:- persistent(queue/1, queue_dir).

queue(first).
queue(second).

main:-
     write('Action ( in(Term). | slip(Term) | out. | list. | halt. ): '),
     read(A),
     (  handle_action(A)
     -> main
     ;  write('Unknown command.'), nl, main ).

handle_action(end_of_file) :-
     halt.
handle_action(halt) :-
     halt.
handle_action(in(Term)) :-
     assertz_fact(queue(Term)).
handle_action(slip(Term)) :-
     asserta_fact(queue(Term)).
handle_action(out) :-
     (  retract_fact(queue(Term))
     -> write('Out '), write(Term)
     ;  write('FIFO empty.') ),
     nl.
handle_action(list) :-
     findall(Term,queue(Term),Terms),
     write('Contents: '), write(Terms), nl.