4.13 Database

SWI-Prolog offers three different database mechanisms. The first one is the common assert/retract mechanism for manipulating the clause database. As facts and clauses asserted using assert/1 or one of its derivatives become part of the program, these predicates compile the term given to them. retract/1 and retractall/1 have to unify a term and therefore have to decompile the program. For these reasons the assert/retract mechanism is expensive. On the other hand, once compiled, queries to the database are faster than querying the recorded database discussed below. See also dynamic/1.

The second way of storing arbitrary terms in the database is using the `recorded database'. In this database terms are associated with a key. A key can be an atom, small integer or term. In the last case only the functor and arity determine the key. Each key has a chain of terms associated with it. New terms can be added either at the head or at the tail of this chain.

Following the Edinburgh tradition, SWI-Prolog provides database keys to clauses and records in the recorded database. As of 5.9.10, these keys are represented by non-textual atoms (`blobs', see section 9.4.7), which makes accessing the database through references safe.

The third mechanism is a special-purpose one. It associates an integer or atom with a key, which is an atom, integer or term. Each key can only have one atom or integer associated with it.

[ISO]abolish(:PredicateIndicator)
Removes all clauses of a predicate with functor Functor and arity Arity from the database. All predicate attributes (dynamic, multifile, index, etc.) are reset to their defaults. Abolishing an imported predicate only removes the import link; the predicate will keep its old definition in its definition module.

According to the ISO standard, abolish/1 can only be applied to dynamic procedures. This is odd, as for dealing with dynamic procedures there is already retract/1 and retractall/1. The abolish/1 predicate was introduced in DEC-10 Prolog precisely for dealing with static procedures. In SWI-Prolog, abolish/1 works on static procedures, unless the Prolog flag iso is set to true.

It is advised to use retractall/1 for erasing all clauses of a dynamic predicate.

abolish(+Name, +Arity)
Same as abolish(Name/Arity). The predicate abolish/2 conforms to the Edinburgh standard, while abolish/1 is ISO compliant.
copy_predicate_clauses(:From, :To)
Copy all clauses of predicate From to To. The predicate To must be dynamic or undefined. If To is undefined, it is created as a dynamic predicate holding a copy of the clauses of From. If To is a dynamic predicate, the clauses of From are added (as in assertz/1) to the clauses of To. To and From must have the same arity. Acts as if defined by the program below, but at a much better performance by avoiding decompilation and compilation.
copy_predicate_clauses(From, To) :-
        head(From, MF:FromHead),
        head(To, MT:ToHead),
        FromHead =.. [_|Args],
        ToHead =.. [_|Args],
        forall(clause(MF:FromHead, Body),
               assertz(MT:ToHead, Body)).

head(From, M:Head) :-
        strip_module(From, M, Name/Arity),
        functor(Head, Name, Arity).
redefine_system_predicate(+Head)
This directive may be used both in module user and in normal modules to redefine any system predicate. If the system definition is redefined in module user, the new definition is the default definition for all sub-modules. Otherwise the redefinition is local to the module. The system definition remains in the module system.

Redefining system predicate facilitates the definition of compatibility packages. Use in other contexts is discouraged.

[ISO]retract(+Term)
When Term is an atom or a term it is unified with the first unifying fact or clause in the database. The fact or clause is removed from the database.
[ISO]retractall(+Head)
All facts or clauses in the database for which the head unifies with Head are removed. If Head refers to a predicate that is not defined, it is implicitly created as a dynamic predicate. See also dynamic/1.49The ISO standard only allows using dynamic/1 as a directive.
[ISO]asserta(+Term)
Assert a fact or clause in the database. Term is asserted as the first fact or clause of the corresponding predicate. Equivalent to assert/1, but Term is asserted as first clause or fact of the predicate.
[ISO]assertz(+Term)
Equivalent to asserta/1, but Term is asserted as the last clause or fact of the predicate.
assert(+Term)
Equivalent to assertz/1. Deprecated: new code should use assertz/1.
asserta(+Term, -Reference)
Asserts a clause as asserta/1 and unifies Reference with a handle to this clause. The handle can be used to access this specific clause using clause/3 and erase/1.
assertz(+Term, -Reference)
Equivalent to asserta/1, asserting the new clause as the last clause of the predicate.
assert(+Term, -Reference)
Equivalent to assertz/2. Deprecated: new code should use assertz/2.
recorda(+Key, +Term, -Reference)
Assert Term in the recorded database under key Key. Key is a small integer (range min_tagged_integer ...max_tagged_integer, atom or compound term. If the key is a compound term, only the name and arity define the key. Reference is unified with an opaque handle to the record (see erase/1).
recorda(+Key, +Term)
Equivalent to recorda(Key, Term, _).
recordz(+Key, +Term, -Reference)
Equivalent to recorda/3, but puts the Term at the tail of the terms recorded under Key.
recordz(+Key, +Term)
Equivalent to recordz(Key, Term, _).
recorded(?Key, ?Value, ?Reference)
True if Value is recorded under Key and has the given database Reference. If Reference is given, this predicate is semi-deterministic. Otherwise, it must be considered non-deterministic. If neither Reference nor Key is given, the triples are generated as in the code snippet below.50Note that, without a given Key, some implementations return triples in the order defined by recorda/2 and recordz/2. See also current_key/1.
        current_key(Key),
        recorded(Key, Value, Reference)
recorded(+Key, -Value)
Equivalent to recorded(Key, Value, _).
erase(+Reference)
Erase a record or clause from the database. Reference is a db-reference returned by recorda/3, recordz/3 or recorded/3, clause/3, assert/2, asserta/2 or assertz/2. Fail silently if the referenced object no longer exists.
instance(+Reference, -Term)
Unify Term with the referenced clause or database record. Unit clauses are represented as Head :- true.
flag(+Key, -Old, +New)
Key is an atom, integer or term. As with the recorded database, if Key is a term, only the name and arity are used to locate the flag. Unify Old with the old value associated with Key. If the key is used for the first time Old is unified with the integer 0. Then store the value of New, which should be an integer, float, atom or arithmetic expression, under Key. flag/3 is a fast mechanism for storing simple facts in the database. The flag database is shared between threads and updates are atomic, making it suitable for generating unique integer counters.51The flag/3 predicate is not portable. Non-backtrackable global variables (nb_setval/2) and non-backtrackable assignment (nb_setarg/3) are more widely recognised special-purpose alternatives for non-backtrackable and/or global states.

4.13.1 Update view

Traditionally, Prolog systems used the immediate update view: new clauses became visible to predicates backtracking over dynamic predicates immediately, and retracted clauses became invisible immediately.

Starting with SWI-Prolog 3.3.0 we adhere to the logical update view, where backtrackable predicates that enter the definition of a predicate will not see any changes (either caused by assert/1 or retract/1) to the predicate. This view is the ISO standard, the most commonly used and the most `safe'.52For example, using the immediate update view, no call to a dynamic predicate is deterministic. Logical updates are realised by keeping reference counts on predicates and generation information on clauses. Each change to the database causes an increment of the generation of the database. Each goal is tagged with the generation in which it was started. Each clause is flagged with the generation it was created in as well as the generation it was erased from. Only clauses with a `created' ... `erased' interval that encloses the generation of the current goal are considered visible.

4.13.2 Indexing databases

The indexing capabilities of SWI-Prolog are described in section 2.17. Summarizing, SWI-Prolog creates indexes for any applicable argument, but only on one argument, and does not index on arguments of compound terms. The predicates below provide building blocks to circumvent the limitations of the current indexing system.

Programs that aim at portability should consider using term_hash/2 and term_hash/4 to design their database such that indexing on constant or functor (name/arity reference) on the first argument is sufficient.

[det]term_hash(+Term, -HashKey)
If Term is a ground term (see ground/1), HashKey is unified with a positive integer value that may be used as a hash key to the value. If Term is not ground, the predicate leaves HashKey an unbound variable. Hash keys are in the range 0 ... 16,777,215, the maximal integer that can be stored efficiently on both 32 and 64 bit platforms.

This predicate may be used to build hash tables as well as to exploit argument indexing to find complex terms more quickly.

The hash key does not rely on temporary information like addresses of atoms and may be assumed constant over different invocations and versions of SWI-Prolog.53Last change: version 5.10.4 Hashes differ between big and little endian machines. The term_hash/2 predicate is cycle-safe.bugAll arguments that (indirectly) lead to a cycle have the same hash key.

[det]term_hash(+Term, +Depth, +Range, -HashKey)
As term_hash/2, but only considers Term to the specified Depth. The top-level term has depth 1, its arguments have depth 2, etc. That is, Depth = 0 hashes nothing; Depth = 1 hashes atomic values or the functor and arity of a compound term, not its arguments; Depth = 2 also indexes the immediate arguments, etc.

HashKey is in the range [0 ...Range-1]. Range must be in the range [1 ... 2147483647]

[det]variant_sha1(+Term, -SHA1)
Compute a SHA1-hash from Term. The hash is represented as a 40-byte hexadecimal atom. Unlike term_hash/2 and friends, this predicate produces a hash key for non-ground terms. The hash is invariant over variable-renaming (see =@=/2) and constants over different invocations of Prolog.bugThe hash depends on word order (big/little-endian) and the wordsize (32/64 bits).

This predicate raises an exception when trying to compute the hash on a cyclic term or attributed term. Attributed terms are not handled because subsumes_chk/2 is not considered well defined for attributed terms. Cyclic terms are not supported because this would require establishing a canonical cycle. That is, given A=[a|A] and B=[a,a|B], A and B should produce the same hash. This is not (yet) implemented.

This hash was developed for lookup of solutions to a goal stored in a table. By using a cryptographic hash, heuristic algorithms can often ignore the possibility of hash collisions and thus avoid storing the goal term itself as well as testing using =@=/2.