Databases & Semantic Web
Facts are tables; rules are views; queries are joins:
42.1 Prolog as a database
Facts are tables; rules are views; queries are joins:
SWI provides JIT indexing on any argument, making large fact bases (millions of facts) practical. library(persistency) journals dynamic facts; qcompile/1 makes .qlf files load quickly.
employee(1, ann, sales, 5000).
employee(2, bob, it, 6000).
dept(sales, 'Building A').
dept(it, 'Building B').
works_in(Name, Building) :- employee(_, Name, D, _), dept(D, Building).
high_earner(N) :- employee(_, N, _, S), S > 5500.
avg_salary(D, Avg) :- aggregate_all(bag(S), employee(_, _, D, S), Ss), sum_list(Ss, T), length(Ss, L), L > 0, Avg is T / L.42.2 External databases
ODBC: library(odbc) — odbc_connect/3, odbc_query/3.
SQLite / PostgreSQL / MySQL via ODBC or packs (prosqlite).
CQL (Constraint Query Language) — SWI library mapping Prolog to SQL.
BerkeleyDB: library(bdb).
Redis: library(redis).
?- odbc_connect('mydsn', C, [user(u), password(p)]),
odbc_query(C, 'SELECT name, age FROM users', row(Name, Age)).42.3 Semantic Web (RDF)
ClioPatria — SWI-based RDF triple store with SPARQL endpoint. TerminusDB is a graph database whose engine was implemented in Prolog (with Rust).
:- use_module(library(semweb/rdf11)).
:- use_module(library(semweb/turtle)).
?- rdf_load('data.ttl').
?- rdf(S, rdf:type, foaf:'Person').
?- rdf_assert(ex:ann, foaf:name, "Ann").42.4 Data formats
library(csv) (csv_read_file/2), library(sgml) (HTML/XML parsing: load_html/3, xpath/3), library(yaml), library(http/json), library(protobufs), library(zlib), library(archive).
?- load_html('page.html', DOM, []), xpath(DOM, //a(@href), Link).
?- csv_read_file('data.csv', Rows, [functor(row), arity(3)]).