Deductive

FernandoFernando SSááenzenz PPéérezrez GrupoGrupo dede ProgramaciProgramacióónn DeclarativaDeclarativa (GPD)(GPD) UniversidadUniversidad ComplutenseComplutense dede MadridMadrid FacultadFacultad dede InformInformááticatica

9/21/2011 PROMETIDOS-CM Summer School 1 / 141 ContentsContents 1. Introduction DES 2. Data Models Relational Logic 3. Fixpoint Semantics Completeness of Datalog w.r.t. RA Stratified Negation 4. Deductive Systems Expressions Constraints Duplicates Aggregates Outer Joins Current DBMS's Limitations 5. Debugging Declarative Debugging Tracers Test Case Generator 6. Other Features 7. Conclusions

9/21/2011 PROMETIDOS-CM Summer School 2 / 141 IntroductionIntroduction DatabasesDatabases (as(as earlyearly asas 1965):1965): Data banks Network (Codasyl model) – Mid 60s BF Goodrich IDMS Hierarchic – 1969 IBM IMS-DB Inverted files – 1970 Software AG ADABAS Relational – 1970 Codd - 1974 IBM System R Deductive – Mid 70s IBM DEDUCE 2 Object oriented – 1988 Objectivity/DB Constraint – 1990 CQL Geodatabases – 1992 ESRI Arc/Info Active – 1996 ACT-Net Consortium Relational object-oriented – 2000 ODMG 3.0 SUN Oracle (Native) XML – 2003 MonetDB/XQuery

9/21/2011 PROMETIDOS-CM Summer School 3 / 141 IntroductionIntroduction

SomeSome concepts:concepts: DatabaseDatabase (DB)(DB) DatabaseDatabase ManagementManagement SystemSystem (DBMS)(DBMS) DataData modelmodel (Abstract) data structures Operations QueryQuery languagelanguage

9/21/2011 PROMETIDOS-CM Summer School 4 / 141 IntroductionIntroduction

QueryQuery languages:languages: OlderOlder Navigational:Navigational: IMSIMS -- CobolCobol RARA TRCTRC TRDTRD SQLSQL (SEQUEL(SEQUEL IBMIBM SystemSystem R)R) DatalogDatalog NewerNewer Navigational:Navigational: XPath/XQueryXPath/XQuery

9/21/2011 PROMETIDOS-CM Summer School 5 / 141 IntroductionIntroduction

DeDe--factofacto standardstandard technologiestechnologies inin databases:databases: “Relational” model SQL But,But, aa currentcurrent trendtrend towardstowards deductivedeductive databases:databases: Datalog 2.0 Conference The resurgence of Datalog inin academiaacademia andand industryindustry Ontologies Semantic Web Social networks Policy languages

9/21/2011 PROMETIDOS-CM Summer School 6 / 141 Introduction.Introduction. SystemsSystems

Classic academic deductive systems: LDL++ (UCLA) CORAL (Univ. of Wisconsin) NAIL! (Stanford University) Ongoing developments Recent commercial deductive systems: DLV (Italy, University of Calabria) LogicBlox (USA) Intellidimension (USA) Semmle (UK) Recent academic deductive systems: 4QL (Warsaw University) bddbddb (Stanford University) ConceptBase (Passau, Aachen, Tilburg Universities, since 1987) XSB (Stony Brook University, Universidade Nova de Lisboa, XSB, Inc., Katholieke Universiteit Leuven, and Uppsala Universitet) DES (Complutense University)

9/21/2011 PROMETIDOS-CM Summer School 7 / 141 Introduction.Introduction. DatalogDatalog EducationalEducational SystemSystem (DES)(DES) YetYet anotheranother system,system, Why?Why? WeWe neededneeded anan interactiveinteractive systemsystem targetedtargeted atat teachingteaching DatalogDatalog inin classroomsclassrooms So,So, whatwhat aa wholewhole setset ofof featuresfeatures wewe wouldwould askask forfor suchsuch aa system?system? A system oriented at teaching User-friendly: Installation Usability Multiplatform (Windows, Linux, Mac, …) Interactive Query languages …

9/21/2011 PROMETIDOS-CM Summer School 8 / 141 DESDES ConcreteConcrete FeaturesFeatures (1/2)(1/2)

Free,Free, OpenOpen--source,source, Multiplatform,Multiplatform, PortablePortable QueryQuery languageslanguages sharingsharing EDB/IDB:EDB/IDB: Datalog following ISO Prolog standard (Recursive) SQL following ANSI/ISO standard DatabaseDatabase updates:updates: SQL DML Commands TemporaryTemporary DatalogDatalog viewsviews DuplicatesDuplicates DeclarativeDeclarative debuggingdebugging ofof DatalogDatalog programsprograms TestTest casecase generationgeneration forfor SQLSQL viewsviews DatalogDatalog andand SQLSQL tracerstracers

9/21/2011 PROMETIDOS-CM Summer School 9 / 141 DESDES ConcreteConcrete FeaturesFeatures (2/2)(2/2) Null value support à la SQL Outer joins for both SQL and Datalog Aggregates Stratified Negation Integrity constraints: Domain Referential integrity Functional dependencies Uniqueness Full-fledged arithmetic Type system for SQL tables and views, and Datalog programs Source-to-source program transformations: Safety Performance (simplifications) Tabling-based implementation

9/21/2011 PROMETIDOS-CM Summer School 10 / 141 SQLSQL

Follows ISO Standard DQL: SELECT … FROM … WHERE WITH RECURSIVE … DML: INSERT … UPDATE … DELETE … DDL: CREATE [OR REPLACE] TABLE … CREATE [OR REPLACE] VIEW … DROP …

9/21/2011 PROMETIDOS-CM Summer School 11 / 141 DatalogDatalog andand SQLSQL inin DESDES

Deductive engine (DE): Tabling implementation Datalog programs are solved by DE Compilation of SQL views and queries to Datalog programs SQL queries are also solved by DE Interoperability is allowed: SQL and Datalog do share the deductive ! Datalog queries ↔ SQL queries Datalog typed relations ↔ SQL tables and views

9/21/2011 PROMETIDOS-CM Summer School 12 / 141 ODBCODBC ConnectionsConnections

New feature since version 2.0 Access to Relational DBMS MySQL MS Access Oracle … SQL statements injected to the DBMS engine Query results are cached by the Datalog engine

9/21/2011 PROMETIDOS-CM Summer School 13 / 141 DESDES asas aa TestTest--BedBed forfor ResearchResearch

TestTest casecase generationgeneration forfor SQLSQL viewsviews DatalogDatalog declarativedeclarative (algorithmic)(algorithmic) debuggingdebugging DatalogDatalog andand SQLSQL tracerstracers NovelNovel proposalproposal forfor outerouter joinsjoins inin DatalogDatalog Theses,Theses, Papers,Papers, AcademiaAcademia…… SeeSee DESDES FactsFacts atat itsits webweb pagepage

9/21/2011 PROMETIDOS-CM Summer School 14 / 141 "Impact"Impact factor"factor"

Up to more than 1,500 downloads a month More than 36,000 downloads since 2004 Month downloads greater than XSB, GNU Prolog, YAP, … More than 10,000 entries in Google First positions in search engines when looking for "Datalog" Moved at the very first position in Datalog entry at Wikipedia It was not me! ☺

9/21/2011 PROMETIDOS-CM Summer School 15 / 141 InstallingInstalling DESDES

DistroDistro underunder GPLGPL inin Sourceforge:Sourceforge: Sources Portable Executables (Windows, Linux, Mac OS X) Portable Bundle including Java IDE (Windows) StartingStarting thethe system.system. Either:Either: From a Prolog interpreter Ciao 1.14.2 GNU Prolog 1.4.0 SICStus Prolog 4.2.0 (Complete support for all features) SWI-Prolog 5.10.5 (Complete support for all features) Simply execute the binary Start the Java application

9/21/2011 PROMETIDOS-CM Summer School 16 / 141 DESDES runningrunning underunder ACIDEACIDE DESDES runningrunning underunder ACIDEACIDE

9/21/2011 PROMETIDOS-CM Summer School 17 / 141 DESDES runningrunning underunder EmacsEmacs

9/21/2011 PROMETIDOS-CM Summer School 18 / 141 DESDES runningrunning asas aa WindowsWindows applicationapplication

9/21/2011 PROMETIDOS-CM Summer School 19 / 141 DESDES runningrunning underunder MacMac OSOS XX SnowSnow LeopardLeopard

9/21/2011 PROMETIDOS-CM Summer School 20 / 141 DESDES runningrunning inin aa LinuxLinux terminalterminal

9/21/2011 PROMETIDOS-CM Summer School 21 / 141 ImplementationImplementation

DES command-line interpreter: Prolog Tabling (Bottom-up Top-down driven) Computation by strata saturations (negation and aggregates) Type system: CLP(FD) Datalog Debugger: Prolog + Java [CGS07] R. Caballero, Y. García-Ruiz, and F. Sáenz-Pérez, A new proposal for debugging datalog programs. WFLP’07 SQL Debugger: CLP(FD) [CGS11b] R. Caballero, Y. García-Ruiz and F. Sáenz-Pérez, "Algorithmic Debugging of SQL Views", Eigth Ershov Invormatics Conference, PSI'11 Test Case Generator: CLP(FD) [CGS10a] R. Caballero, Y. García-Ruiz, and F. Sáenz-Pérez, Applying Constraint Logic Programming to SQL Test Case Generation, FLOPS 2010 ACIDE: Java A Configurable IDE (LaTeX, SQL, Prolog, Datalog, …) [Sae07b] F. Sáenz-Pérez, “ACIDE: An Integrated Development Environment Configurable for LaTeX”, The PracTeX Journal, 2007

9/21/2011 PROMETIDOS-CM Summer School 22 / 141 IntroductionIntroduction

GoalsGoals ofof thisthis talk:talk: Databases:Databases: FromFrom relationalrelational toto deductivedeductive (Declarative)(Declarative) QueryQuery Languages:Languages: FromFrom SQLSQL toto DatalogDatalog SQL: Many functionalities Datalog: Neater formulations How:How: DataData modelsmodels ConcreteConcrete system:system: DESDES

9/21/2011 PROMETIDOS-CM Summer School 23 / 141 RelationalRelational ModelModel

Edgar.Edgar. F.F. (Ted)(Ted) CoddCodd (1923(1923--2003)2003) inin thethe earlyearly seventies.seventies. [[ TuringTuring AwardAward ––19811981 ]] SimpleSimple andand elegantelegant modelmodel withwith aa mathematicalmathematical basis.basis. Language:Language: RelationalRelational algebraalgebra operationsoperations QueryQuery optimizationoptimization andand executionexecution DatabaseDatabase standardstandard ANSI/ISOANSI/ISO SQLSQL CurrentCurrent DBMSsDBMSs supportsupport relationalrelational modelmodel Warning:Warning: TheyThey areare flawedflawed extensions.extensions.

9/21/2011 PROMETIDOS-CM Summer School 24 / 141 RelationalRelational Model.Model. ConceptsConcepts

RelationRelation schemaschema RelationRelation namename (Typed)(Typed) AttributesAttributes Domains RelationRelation instanceinstance ActualActual valuesvalues RelationRelation constraintsconstraints PrimaryPrimary keykey ForeignForeign keykey

9/21/2011 PROMETIDOS-CM Summer School 25 / 141 RelationalRelational Model.Model. LanguagesLanguages

CalculusCalculus--orientedoriented LanguagesLanguages TupleTuple RelationalRelational CalculusCalculus DomainDomain RelationalRelational CalculusCalculus AlgebraAlgebra--orientedoriented LanguageLanguage RelationalRelational AlgebraAlgebra (RA)(RA)

9/21/2011 PROMETIDOS-CM Summer School 26 / 141 RelationalRelational AlgebraAlgebra

BasicBasic Operations:Operations:

SelectionSelection σσCondition((RelationRelation))

ProjectionProjection ππAttributes((RelationRelation))

RenamingRenaming ρρSchema((RelationRelation)) CartesianCartesian productproduct LRLR X RRRR UnionUnion LRLR ∪∪ RRRR DifferenceDifference LRLR -- RRRR

9/21/2011 PROMETIDOS-CM Summer School 27 / 141 StructuredStructured QueryQuery LanguageLanguage (SQL)(SQL)

BasedBased onon RelationalRelational Algebra:Algebra:

SELECTSELECT σσCondition((RelationRelation))

ProjectionProjection listlist ππAttributes((RelationRelation))

AS,AS, WITHWITH ρρSchema((RelationRelation)) FROMFROM LRLR X RRRR UNIONUNION LRLR ∪∪ RRRR EXCEPTEXCEPT LRLR -- RRRR

9/21/2011 PROMETIDOS-CM Summer School 28 / 141 WhatWhat relationalrelational languageslanguages cancan dodo

RowRow filteringfiltering TupleTuple filteringfiltering BuildBuild newnew relationsrelations byby combinationscombinations ExpressionExpression evaluationevaluation (Generalized(Generalized projection)projection)

9/21/2011 PROMETIDOS-CM Summer School 29 / 141 WhatWhat relationalrelational languageslanguages cannotcannot dodo

AreAre wewe runningrunning lowlow onon anyany partsparts neededneeded toto buildbuild aa ZX600ZX600 sportssports car?car? WhatWhat isis thethe totaltotal componentcomponent andand assemblyassembly costcost toto buildbuild aa ZX600ZX600 atat today'stoday's partpart prices?prices?

WhatWhat dodo wewe simplysimply needneed isis recursionrecursion

9/21/2011 PROMETIDOS-CM Summer School 30 / 141 ExampleExample bike 21 part subpart wheel frame number 16 1 1 1 bike wheel 2 spoke tire seat pedal bike frame 1 11 frame seat 1 rim tube frame pedal 1 wheel spoke 16 FindFind componentscomponents ofof aa bikebike wheel tire 1 tire rim 1 tire tube 1

Assembly instance 9/21/2011 PROMETIDOS-CM Summer School 31 / 141 WhatWhat relationalrelational languageslanguages cannotcannot dodo

Intuitively,Intuitively, wewe mustmust joinjoin AssemblyAssembly withwith itselfitself toto deducededuce thatthat bikebike containscontains spokespoke andand tire.tire. TakesTakes usus oneone levellevel downdown AssemblyAssembly hierarchy.hierarchy. ToTo findfind componentscomponents thatthat areare oneone levellevel deeperdeeper (e.g.,(e.g., rim),rim), needneed anotheranother join.join. ToTo findfind allall components,components, needneed asas manymany joinsjoins asas therethere areare levelslevels inin thethe givengiven instance!instance! ForFor anyany relationalrelational algebraalgebra expression,expression, wewe cancan createcreate anan AssemblyAssembly instanceinstance forfor whichwhich somesome answersanswers areare notnot computedcomputed byby includingincluding moremore levelslevels thanthan thethe numbernumber ofof joinsjoins inin thethe expression!expression!

9/21/2011 PROMETIDOS-CM Summer School 32 / 141 LogicLogic asas aa DataData ModelModel

RelationalRelational databasesdatabases distinguishdistinguish betweenbetween DDLDDL andand DMLDML DDL is for creating schemas or views DML is for maintaining data and queries

InIn deductivedeductive databasesdatabases bothboth datadata andand queriesqueries areare specifiedspecified byby formulasformulas

9/21/2011 PROMETIDOS-CM Summer School 33 / 141 DeductiveDeductive DatabaseDatabase

A deductive database consists of facts and rules The set of facts is called extensional database (EDB) If no functions are used in the facts, it can be represented as a simple relational database table The set of rules is called intensional database (IDB) Analogous to views in relational databases

9/21/2011 PROMETIDOS-CM Summer School 34 / 141 FOLFOL RecallRecall

A logical language ℒ is given by the signature ℒ = (Γ, Ω, Π, Χ) Γ : All constant symbols Ω : All functional symbols Π : All predicate symbols Χ : All variable symbols An Interpretation captures the semantics of ℒ An interpretation assigns each term to an element of some universe of discourse An interpretation assigns a truth value to each formula i.e., decides which statements are true and which are false

9/21/2011 PROMETIDOS-CM Summer School 35 / 141 FOLFOL RecallRecall

Model-Theoretic Interpretation of rules Rules define possible worlds or models A model of a set of rules is an interpretation that makes true all rules There are many models for a set of rules Without negation, a unique minimal model can be found

9/21/2011 PROMETIDOS-CM Summer School 36 / 141 FOLFOL RecallRecall

Example: Substitution ρ={X/1}: (1) p(X) ← q(X) (1) p(1) ← q(1) : true ← true : true (2) q(X) ← r(X) (2) q(1) ← r(1) : true ← true : true M1: Substitution ρ={X/2}: r(1), (1) p(2) ← q(2) : true ← true : true q(1), (2) q(2) ← r(2) : true ← false : true p(1), Substitution ρ={X/3}: q(2), (1) p(3) ← q(3) : true ← false : true p(2), (2) q(3) ← r(3) : true ← false : true p(3) are true Substitution ρ={X/i} for all other i: false, otherwise (1) p(i) ← q(i) : false ← false : true (2) q(i) ← r(i) : false ← false : true

9/21/2011 PROMETIDOS-CM Summer School 37 / 141 FOLFOL RecallRecall

Example (ctd.): M2 is a minimal model (1) p(X) ← q(X) No true fact can be extracted (2) q(X) ← r(X) from M2 and resulting a model consistent with {r(1)} (3) r(1) M2: r(1), q(1), p(1) are true false, otherwise

9/21/2011 PROMETIDOS-CM Summer School 38 / 141 FOLFOL andand DatabasesDatabases

WhatWhat aa typicaltypical databasedatabase useruser wouldwould expectexpect fromfrom aa queryquery language?language? FiniteFinite data,data, finitefinite computationscomputations (terminating(terminating queries)queries) No terms or bound depth Still, be aware of built-in infinite relations! AllAll answeranswer tuplestuples atat onceonce Prolog returns several answers upon backtracking

9/21/2011 PROMETIDOS-CM Summer School 39 / 141 FOLFOL andand DatabasesDatabases

RestrictRestrict FOLFOL allowingallowing onlyonly HornHorn clausesclauses andand nonnon--recursiverecursive typedtyped functionsfunctions Ground instances are thus Horn clauses Check for unsatisfiability of finite subsets of Herbrand expansion is in P Herbrand expansion is finite as the Herbrand universe is finite

9/21/2011 PROMETIDOS-CM Summer School 40 / 141 LogicLogic asas aa DataData ModelModel

So, every predicate is written by Horn clauses: ∀(L1 ∨ L2 ∨ … ∨ Ln), Li ∈ Lℒ With atomic formulae Li and at most one positive literal Lj Logic programming introduced a slightly different notation of Horn clauses for simplicity Lj ← L1 , …, Lj-1, Lj+1, …, Ln. Where: ← is understood as implication , as conjunction . denotes the end of a clause

9/21/2011 PROMETIDOS-CM Summer School 41 / 141 DatalogDatalog

Datalog is a query and rule language specifically defined for deductive databases Syntactically similar to Prolog Introduced around 1978 for academic database research by Hervé Gallaire and Jack Minker Used as the main foundation for expert systems theory during the 1980ies

9/21/2011 PROMETIDOS-CM Summer School 42 / 141 DatalogDatalog

AA databasedatabase queryquery languagelanguage stemmingstemming fromfrom PrologProlog

Prolog Datalog RA Predicate Relation Relation Goal Query Expression

PrologProlog andand DatalogDatalog areare basedbased ofof FirstFirst OrderOrder LogicLogic (FOL)(FOL) AKA Predicate Logic

9/21/2011 PROMETIDOS-CM Summer School 43 / 141 DatalogDatalog

DatalogDatalog differsdiffers fromfrom Prolog:Prolog: Datalog does not allow function symbols in arguments Facts are ground Meaning of a Datalog relation follows the model-theoretic point-of-view Intensionally (Rules or Clauses) Extensionally (Facts) Datalog is truly declarative: Clause order is irrelevant Order of literals in a body is irrelevant No extra-logical constructors as the feared cut

9/21/2011 PROMETIDOS-CM Summer School 44 / 141 DatalogDatalog SyntaxSyntax

Program: Set of rules. Rule: head :- body. ground_head. Head: Positive atom. Body: Conjunctions (,) and disjunctions (;) of literals Literal: Atom, Built-in (>, <, …). Query: Literal with variables or constants in arguments Body (Conjunctive queries, …)

9/21/2011 PROMETIDOS-CM Summer School 45 / 141

DatalogDatalog tom grace

ExampleExample jack amy tony carolI

Facts: fred carolII father(tom,amy). father(jack,fred). carolIII father(tony,carolII). father(fred,carolIII). mother(graceI,amy). mother(amy,fred). mother(carolI,carolII). Query: mother(carolII,carolIII). parent(X,Y)

Rules: Minimal model for parent: { parent(X,Y) :- father(X,Y). (tom,amy), (grace,amy), (jack,fred), parent(X,Y) :- mother(X,Y). (amy,fred), … }

9/21/2011 PROMETIDOS-CM Summer School 46 / 141

tom grace RecursionRecursion jack amy tony carolI father(tom,amy). fred carolII father(jack,fred). father(tony,carolII). father(fred,carolIII). carolIII mother(graceI,amy). mother(amy,fred). mother(carolI,carolII). mother(carolII,carolIII). parent(X,Y) :- father(X,Y). ancestor(tom,X) parent(X,Y) :- mother(X,Y). { ancestor(X,Y) :- ancestor(tom,amy), parent(X,Y). ancestor(tom,carolIII), ancestor(X,Y) :- ancestor(tom,fred) parent(X,Z), } ancestor(Z,Y).

9/21/2011 PROMETIDOS-CM Summer School 47 / 141 FixpointFixpoint SemanticsSemantics ofof RecursiveRecursive DatalogDatalog Let f be a function that takes values from domain D and returns values from D. A value v in D is a fixpoint of f if f(v)=v. ConsiderConsider thethe fnfn double+double+,, whichwhich isis appliedapplied toto aa setset ofof integersintegers andand returnsreturns aa setset ofof integersintegers (i.e.,(i.e., DD isis thethe setset ofof allall setssets ofof integers).integers). E.g.,E.g., double+({1,2,5})={2,4,10}double+({1,2,5})={2,4,10} UnionUnion {1,2,5}{1,2,5} TheThe setset ofof allall integersintegers isis aa fixpointfixpoint ofof double+.double+. TheThe setset ofof allall eveneven integersintegers isis anotheranother fixpointfixpoint ofof double+double+;; itit isis smallersmaller thanthan thethe firstfirst fixpoint.fixpoint.

9/21/2011 PROMETIDOS-CM Summer School 48 / 141 LeastLeast FixpointFixpoint SemanticsSemantics

TheThe leastleast fixpointfixpoint ((lfplfp)) ofof aa functionfunction ff isis aa fixpointfixpoint vv ofof ff suchsuch thatthat everyevery otherother fixpointfixpoint ofof ff isis smallersmaller thanthan oror equalequal toto vv.. InIn general,general, therethere maymay bebe nono leastleast fixpointfixpoint (we(we couldcould havehave twotwo minimalminimal fixpoints,fixpoints, neitherneither ofof whichwhich isis smallersmaller thanthan thethe other).other). IfIf wewe thinkthink ofof aa DatalogDatalog programprogram asas aa functionfunction thatthat isis appliedapplied toto aa setset ofof tuplestuples andand returnsreturns anotheranother setset ofof tuples,tuples, thisthis functionfunction (fortunately!)(fortunately!) alwaysalways hashas aa leastleast fixpoint.fixpoint.

9/21/2011 PROMETIDOS-CM Summer School 49 / 141 UnrestrictedUnrestricted VariablesVariables

Problem of variables in heads of rules Consider a rule p(X) :- r(Y). What does this mean? If there is a substitution for Y making r(Y) true, then p(X) is true for all possible substitutions for X? If r(Y) is true for all possible substitutions of Y, then p(X) is true?? Or only for Y=X??? Problem with (built-in) comparison operators: less(X,Y) :- X < Y There are infinite pairs that commit to X < Y

9/21/2011 PROMETIDOS-CM Summer School 50 / 141 SafetySafety

A rule is safe if all its variables are limited (range restricted) A limited variable in a rule is defined as: Any variable in a user-defined predicate in a subgoal is limited Any variable X that occurs in a subgoal X=a or a=X is limited A variable X is limited if it occurs in a subgoal X=Y or Y=X, where Y is already known to be limited Bottomline: Any head variable and variables in built-ins become ground

9/21/2011 PROMETIDOS-CM Summer School 51 / 141 CompletenessCompleteness ofof DatalogDatalog w.r.t.w.r.t. RARA

Recursion is appealing but, Is Datalog as expressive as RA and SQL? Let’s see…

9/21/2011 PROMETIDOS-CM Summer School 52 / 141 SelectionSelection s(sno INTEGER, name STRING)

RA:

σσsno=1((ss))

SQL: SELECT name FROM s WHERE sno=1;

Datalog: s(1,Y).

9/21/2011 PROMETIDOS-CM Summer School 53 / 141 ProjectionProjection s(sno INTEGER, name STRING)

RA:

ππname((ss))

SQL: SELECT name FROM s;

Datalog: s(_X,Y).

9/21/2011 PROMETIDOS-CM Summer School 54 / 141 RenamingRenaming s(sno INTEGER, name STRING) RA:

ρρprojection((ππname ((ss))))

SQL: WITH projection(name) AS (SELECT name FROM s) SELECT * FROM projection;

Datalog: projection(Y) :- s(X,Y).

9/21/2011 PROMETIDOS-CM Summer School 55 / 141 CartesianCartesian ProductProduct s(sno INT, name STRING) sp(sno INT, pno INT)

RA: ss X spsp

SQL: SELECT * FROM s,sp;

Datalog: s(X,Y), sp(U,V).

9/21/2011 PROMETIDOS-CM Summer School 56 / 141 SetSet UnionUnion s(sno INT, name STRING) q(sno INT, name STRING) RA: ss ∪∪ qq

SQL: SELECT * FROM s UNION SELECT * FROM q;

Datalog: s(X,Y) ; q(U,V).

9/21/2011 PROMETIDOS-CM Summer School 57 / 141 SetSet DifferenceDifference s(sno INT, name STRING) q(sno INT, name STRING) RA: ss -- qq

SQL: SELECT * FROM s EXCEPT SELECT * FROM q;

Datalog: s(X,Y), not(q(X,Y)).

9/21/2011 PROMETIDOS-CM Summer School 58 / 141 ExpressiveExpressive PowerPower

So,So, forfor DatalogDatalog toto bebe completecomplete w.r.t.w.r.t. RA,RA, aa formform ofof (dreaded)(dreaded) negationnegation mustmust bebe facedfaced ThereThere areare severalseveral DatalogDatalog proposalsproposals

9/21/2011 PROMETIDOS-CM Summer School 59 / 141 DatalogDatalog LanguageLanguage ClassesClasses

Depending on the use of functions and negation several Datalog language classes can be distinguished Datalogneg programs do not contain function symbols Datalogf programs (or definite programs) do not contain negative literals Datalog programs contain neither negative literals nor function symbols

9/21/2011 PROMETIDOS-CM Summer School 60 / 141 EquivalentEquivalent DBDB LanguagesLanguages

Relational Algebra Relational Calculus Non-recursive Datalog with Negation

9/21/2011 PROMETIDOS-CM Summer School 61 / 141 NegationNegation inin RuleRule BodiesBodies

The negation of a relation stands for its complement, but this is rather not a well-defined term Finding a complement must be w.r.t. to a domain RA does the trick with the difference operator (both instance relations are ground) Even knowing the actual domain, the complement may be infinite X: integer, not(p(X))

9/21/2011 PROMETIDOS-CM Summer School 62 / 141 NegationNegation andand SafetySafety

Also, unlimited variables are a problem bachelor(X) :- male(X), not(married(X,Y)) Joining male(X) with the complement of married yields all tuples (X,Y) such that X is a male who is not married to absolutely everybody in the universe

DES> /assert bachelor(X) :- male(X), not(married(X,Y)) Error: not(married(X,Y)) might not be correctly computed because of the unrestricted variable(s): [Y]

So,So, variablesvariables inin negationnegation mustmust bebe limitedlimited

9/21/2011 PROMETIDOS-CM Summer School 63 / 141 NegationNegation inin RuleRule BodiesBodies

Limiting variables is a need but does not completely solve the problem with negation If negation is allowed, there might not be a single fixed point, but several ones If so, what does a logic program mean? Example: p(X) :- r(X), not(q(X)). q(X) :- r(X), not(p(X)). r(1). Possible solutions (both are minimal fixed points): S1: P=∅, Q={1} S2: P={1}, Q= ∅ We need a way to choose the intended fixpoint for safe programs.

9/21/2011 PROMETIDOS-CM Summer School 64 / 141 StratifiedStratified NegationNegation

Stratified negation is a property that some programs enjoy, which help to deal with the problem of many minimal fixpoints. Predicate dependency: T depends on S if some rule with T in the head contains S or (recursively) some predicate that depends on S, in the body. A predicate dependency graph (PDG) is this way defined Stratified program: If T depends on not S, then S cannot depend on T (or not T). If a program is stratified, predicates in the program can be partitioned into strata: Stratum 0: All EDB predicates. Stratum i: Predicates defined in terms of tables in Stratum i and lower strata. If T depends on not S, S is in a lower stratum than T.

9/21/2011 PROMETIDOS-CM Summer School 65 / 141 StratifiedStratified Negation.Negation. SafetySafety

Stratified negation still requires safety. NegatedNegated goalsgoals areare notnot allowedallowed toto bebe rangerange restrictors,restrictors, theythey ratherrather needneed limitedlimited variables.variables.

9/21/2011 PROMETIDOS-CM Summer School 66 / 141 StratifiedStratified SemanticsSemantics forfor StratifiedStratified ProgramsPrograms TheThe semanticssemantics ofof aa stratifiedstratified programprogram isis givengiven byby oneone ofof thethe minimalminimal fixpoints,fixpoints, whichwhich cancan bebe identifiedidentified byby thethe followingfollowing operationaloperational definition:definition: First,First, computecompute thethe leastleast fixpointfixpoint ofof allall predicatespredicates inin StratumStratum 1.1. (Stratum(Stratum 00 predicatespredicates areare fixed.)fixed.) Then,Then, computecompute thethe leastleast fixpointfixpoint ofof predicatespredicates inin StratumStratum 2;2; thenthen thethe lfplfp ofof predicatespredicates inin StratumStratum 3,3, andand soso on,on, stratumstratum--byby--stratum.stratum.

9/21/2011 PROMETIDOS-CM Summer School 67 / 141 StratifiedStratified Semantics.Semantics. PerformancePerformance

Typically,Typically, aa databasedatabase useruser doesdoes notnot needneed allall thethe intensionalintensional data.data. Rather,Rather, hehe queriesqueries viewsviews ofof interestinterest So,So, DESDES implementsimplements tablingtabling (cf.(cf. M.M. CarroCarro talk)talk) TopTop--downdown driven,driven, bottombottom--upup computationcomputation RestrictRestrict PDGPDG toto thethe query,query, findfind aa stratificationstratification andand computecompute onlyonly thethe involvedinvolved predicatespredicates ItIt mightmight bebe thethe casecase ofof loadingloading aa nonnon--stratifiablestratifiable programprogram butbut findingfinding aa stratificationstratification forfor aa givengiven queryquery Tabling,Tabling, asas alreadyalready introduced,introduced, provides:provides: Termination Performance

9/21/2011 PROMETIDOS-CM Summer School 68 / 141 NonNon--stratifiablestratifiable Example:Example: RussellRussell ParadoxParadox

The barber in a town shaves every person who does not shave himself DES-Datalog> man(X) DES-Datalog> /c russell Info: Consulting russell... Info: Stratifiable shaves(barber,M) :- man(M), not(shaves(M,M)). subprogram found for man(barber). the given query. man(mayor). { shaved(M) :- shaves(barber,M). man(barber), end_of_file. man(mayor) Info: 4 rules consulted. } Warning: Non stratifiable program. Info: 2 tuples computed. DES-Datalog> shaves(X,Y) Warning: Unable to ensure correctness for this query. { shaves(barber,mayor) } Info: 1 tuple computed. Undefined: But, warning: DES does not offer { shaves(barber,barber) complete support for a 3VL } Info: 1 tuple undefined.

9/21/2011 PROMETIDOS-CM Summer School 69 / 141 IsIs ThatThat AllAll aboutabout Negation,Negation, Folks?Folks?

NegationNegation isis aa hugehuge sourcesource ofof problemsproblems andand fixesfixes FurtherFurther proposals:proposals: Stable Model Semantics (Gelfond) Based on Moore’s autoepistemic logic 2VL and 3VL DLV, ASP (Answer Set Programming) Well-founded Semantics (WFS) It relies on unfounded sets to deduce negative information XSB 4-Valued Logic (4VL) ‘true’, ‘false’, ‘inconsistent’ and ‘unknown’ 4QL

9/21/2011 PROMETIDOS-CM Summer School 70 / 141 PracticalPractical DatabaseDatabase SystemsSystems

What we do need are systems that solve everyday problems, not toy examples First, expressive power does not only depend on recursion, but on other needs, as: Evaluation of expressions (arithmetic, strings, …) (Strong) Constraints Duplicates Aggregates NULL-related operators … Second, efficient systems Inferring method Indexing Scalability … 9/21/2011 PROMETIDOS-CM Summer School 71 / 141 EvaluationEvaluation ofof ExpressionsExpressions ArithmeticArithmetic expressionsexpressions areare usuallyusually evaluatedevaluated byby aa couplecouple ofof methodsmethods inin DDB:DDB: Built-in predicate: X is Expression DES-Datalog> X is sqrt(2) { 1.4142135623730951 is sqrt(2) } Info: 1 tuple computed. Equality: LeftExpr = RightExpr (DLV provides limited support) DES-Datalog> 2+1=Y { 2 + 1 = 3 } Info: 1 tuple computed. AsAs expected,expected, theythey areare sourcesource oror unsafetyunsafety…… 9/21/2011 PROMETIDOS-CM Summer School 72 / 141 ArithmeticArithmetic UnsafetyUnsafety DES-Datalog> p(X) p(0). Prolog interruption (h for help)? a p(X) :- | ?- des. p(Y), DES-Datalog> /list_et X is Y + 1. Answers: { p(0), Unlimited tuples is(N,N+1) become p(1), computed (although not stored) p(2), p(3), Unbounded arithmetic p(4), Try the query, press Ctrl-C, and type: p(5), p(6), des. p(7), /list_et. p(8), /list_et. p(9), …

9/21/2011 PROMETIDOS-CM Summer School 73 / 141 IntegrityIntegrity ConstraintsConstraints Integrity constraints (IC): Strong constraints as known in databases Do not mix up with constraints as in CLP(D) ! Usual IC: Type (domain) Primary key Foreign key Existency constraints Check constraints Not so-usual IC: Candidate key Functional dependencies User-defined integrity constraints Expressed in DES as either Datalog assertions or SQL statements

9/21/2011 PROMETIDOS-CM Summer School 74 / 141 TypesTypes

varchar String of unbounded TypesTypes stemmedstemmed fromfrom SQLSQL string length char(N) varchar(N) String with length up to N

char String with length 1

integer Integer number int float real Real number

AlternativeAlternative DatalogDatalog syntax:syntax:

DES-Datalog> :- type(p,[int,string]) DES-Datalog> :- type(p(int,string))

9/21/2011 PROMETIDOS-CM Summer School 75 / 141 Types.Types. IntensionalIntensional DatabaseDatabase

Predicates defined by rules (IDB)

DES-Datalog> /listing s(a). t(1). t(X) :- s(X). Info: 3 rules listed.

DES-Datalog> :-type(t,[int]) Error: No type tuple covers all the loaded rules for t/1: t(1). t(X) :- s(X). Info: 2 rules listed.

9/21/2011 PROMETIDOS-CM Summer School 76 / 141 Types.Types. PropositionalPropositional RelationsRelations

PredicatesPredicates defineddefined byby rulesrules (IDB)(IDB)

DES-Datalog> :-type(a,[])

DES-Datalog> /dbschema a

Info: Table: * a

9/21/2011 PROMETIDOS-CM Summer School 77 / 141 TypesTypes vs.vs. DomainsDomains TypeType assertionsassertions andand SQLSQL tabletable creationcreation areare alternativealternative syntaxsyntax forfor imposingimposing typetype constraintsconstraints

SQL: CREATE TABLE s(sno INT, name VARCHAR(10));

Datalog: :-type(s(sno:int, name:varchar(10))).

DES-Datalog> /dbschema Info: Table(s): * s(sno:number(integer),name:string(varchar(10))) Info: No views. Info: No integrity constraints.

9/21/2011 PROMETIDOS-CM Summer School 78 / 141 ExistencyExistency ConstraintConstraint AnAn existencyexistency constraintconstraint requiresrequires concreteconcrete valuesvalues forfor instancesinstances TheThe NULLNULL valuevalue asas inin relationalrelational databasesdatabases inin supportedsupported inin DESDES (more(more onon thisthis later)later) SQL: CREATE TABLE s(sno INT, name VARCHAR(10) NOT NULL);

Datalog: :-type(s(sno:int, name:varchar(10))). :-nn(s,[name]).

DES-Datalog> /assert s(1,null) Error: Not null violation s.[name]

9/21/2011 PROMETIDOS-CM Summer School 79 / 141 PrimaryPrimary KeyKey ConstraintConstraint AA primaryprimary keykey (PK)(PK) constraintconstraint requiresrequires uniqueunique combinationscombinations ofof concreteconcrete valuesvalues forfor instancesinstances SQL: CREATE TABLE s(sno INT PRIMARY KEY, name VARCHAR(10));

Datalog: :-type(s(sno:int, name:varchar(10))). :-pk(s,[sno]).

DES-Datalog> /assert s(1,'wheel') DES-Datalog> /assert s(1,'spoke') Error: Primary key violation s.[sno] when trying to insert: s(1,spoke)

9/21/2011 PROMETIDOS-CM Summer School 80 / 141 CandidateCandidate KeyKey ConstraintConstraint

AKAAKA UniquenessUniqueness constraintconstraint SimilarSimilar toto PKPK No direct support in standard SQL. You must use non- duplicated indexes (not yet supported by DES): CREATE INDEX s_index FOR s ON sno NO DUPLICATES;

But, DES does provide (extension to standard): CREATE TABLE s(sno INT, name VARCHAR(10) CANDIDATE KEY);

Datalog: :-type(s(sno:int, name:varchar(10))). :-ck(s,[name]).

9/21/2011 PROMETIDOS-CM Summer School 81 / 141 ForeignForeign KeyKey ConstraintConstraint

ValuesValues inin aa givengiven setset ofof columnscolumns ofof aa relationrelation mustmust existexist alreadyalready inin thethe columnscolumns declareddeclared inin thethe primaryprimary keykey constraintconstraint ofof anotheranother relation.relation.

SQL: CREATE TABLE n(name VARCHAR(10) PRIMARY KEY); CREATE TABLE s(sno INT, name VARCHAR(10) FOREIGN KEY n);

Datalog: :-type(n(name:varchar(10))). :-pk(n,[name]). :-type(s(sno:int, name:varchar(10))). :-fk(s,[name],n,[name]). 9/21/2011 PROMETIDOS-CM Summer School 82 / 141 FunctionalFunctional DependencyDependency ConstraintConstraint

GivenGiven aa setset ofof attributesattributes AA11 ofof aa relationrelation RR,, theythey functionallyfunctionally determinedetermine anotheranother setset AA2,2, i.e.,i.e., eacheach tupletuple ofof valuesvalues ofof AA11 inin RR isis associatedassociated withwith preciselyprecisely oneone tupletuple ofof valuesvalues AA22 inin thethe samesame tupletuple ofof RR

No provision in SQL Standard

Datalog: DES-Datalog> :-type(p,[a:int,b:int]) DES-Datalog> :-fd(p,[a],[b]) DES-Datalog> /dbschema p Info: Table: * p(a:number(integer),b:number(integer)) - FD: [a] -> [b]

9/21/2011 PROMETIDOS-CM Summer School 83 / 141 UserUser--defineddefined IntegrityIntegrity ConstraintsConstraints

SQL:SQL: CHECK constraints (not supported by DES, yet) Triggers

CREATE TABLE t(c INT CHECK (c BETWEEN 0 AND 10));

Datalog:

DES-Datalog> :-type(t,[c:int]) DES-Datalog> :-t(X),(X<0;X>10) DES-Datalog> /assert t(11) Error: Integrity constraint violation. ic(X) :- t(X),(X < 0 ; X > 10). Offending values in database: [ic(11)]

9/21/2011 PROMETIDOS-CM Summer School 84 / 141 UserUser--defineddefined IntegrityIntegrity ConstraintsConstraints

DES-Datalog> /consult paths Info: Consulting paths... edge(a,b). a edge(a,c). edge(b,a). b c edge(b,d). path(X,Y) :- path(X,Z), edge(Z,Y). path(X,Y) :- edge(X,Y). d end_of_file. Info: 6 rules consulted. DES-Datalog> :-path(X,X) Error: Integrity constraint violation. ic(X) :- path(X,X). Offending values in database: [ic(b),ic(a)] Info: Constraint has not been asserted.

9/21/2011 PROMETIDOS-CM Summer School 85 / 141 DuplicatesDuplicates

SQLSQL isis notnot setset--oriented,oriented, ratherrather itit allowsallows duplicatesduplicates inin basebase relationsrelations andand queryquery outcomesoutcomes ItIt doesdoes moremore thanthan RARA andand DatalogDatalog So,So, forfor supportingsupporting SQLSQL wewe need:need: Multisets or Bags Duplicate elimination But,But, duplicatesduplicates suffersuffer issues,issues, andand howeverhowever allall practicalpractical RDBMSsRDBMSs dodo supportsupport duplicatesduplicates "If something is true, saying it twice doesn't make it any more true." [E.F. Codd]

9/21/2011 PROMETIDOS-CM Summer School 86 / 141 Duplicates.Duplicates. SomeSome IssuesIssues

Identifier and name of suppliers: s(sno INT, name STRING) Which supplier supplies a given part: sp(sno,pno)

SELECT sno FROM s WHERE sno IN (SELECT sno FROM sp)

SELECT sno FROM s NATURAL INNER JOIN sp

Semantically equivalent queries return a different number of tuples Also, they preclude some optimizations and make this process cumbersome 9/21/2011 PROMETIDOS-CM Summer School 87 / 141 DuplicatesDuplicates asas ofof DESDES

Duplicates are disabled by default DES-Datalog> /duplicates on DES-Datalog> /assert t(1) DES-Datalog> /assert t(1) DES-Datalog> t(X) { t(1), t(1) } Info: 2 tuples computed.

Rules can also be source of duplicates, as in: DES-Datalog> /assert s(X):-t(X) DES-Datalog> s(X) { s(1), s(1) } Info: 2 tuples computed. 9/21/2011 PROMETIDOS-CM Summer School 88 / 141 DuplicatesDuplicates asas ofof DESDES

Duplicates even in recursive rules (LDL does not allow this)

DES-Datalog> /assert t(X):-t(X) DES-Datalog> t(X) { t(1), t(1), t(1), t(1) } Info: 4 tuples computed.

No SQL implementation support this

9/21/2011 PROMETIDOS-CM Summer School 89 / 141 DuplicatesDuplicates asas ofof DESDES

Discarding duplicates with metapredicates: distinct/1 distinct/2

DES-Datalog> distinct(t(X)) Info: Processing: answer(X) :- distinct(t(X)). { answer(1) } Info: 1 tuple computed.

SQL

DES-Datalog> select distinct * from t answer(t.a) -> { answer(1) } Info: 1 tuple computed. 9/21/2011 PROMETIDOS-CM Summer School 90 / 141 SafetySafety andand DuplicatesDuplicates

SetSet variablesvariables inin duplicateduplicate metapredicatesmetapredicates areare notnot boundbound

distinct([X],t(X,Y))

Unsafe goal:

distinct([X],t(X,Y)), s(Y)

DES-Datalog> distinct([X],t(X,Y)), s(Y) Error: Incorrect use of shared set variables in metapredicate: [Y] DES-Datalog> /safe on DES-Datalog> distinct([X],t(X,Y)), s(Y) Info: Processing: answer(X,Y,C) :- s(Y), distinct([X],t(X,Y)).

9/21/2011 PROMETIDOS-CM Summer School 91 / 141 AggregatesAggregates

AggregateAggregate functions:functions: countcount –– COUNTCOUNT(*)(*) count(Vcount(V)) –– COUNT(C)COUNT(C) min(Vmin(V)) -- MIN(C)MIN(C) max(Vmax(V)) -- MAX(C)MAX(C) sum(Vsum(V)) -- SUM(C)SUM(C) avg(Varavg(Var)) -- AVG(C)AVG(C) times(Vartimes(Var)) -- NoNo SQLSQL counterpartcounterpart

9/21/2011 PROMETIDOS-CM Summer School 92 / 141 AggregatesAggregates

MetapredicateMetapredicate group_by/3

group_by( Relation_A, % FROM / WHERE [Var_1,…,Var_n], % GroupingGrouping columnscolumns Relation_B) % HAVING / ProjectionProjection

9/21/2011 PROMETIDOS-CM Summer School 93 / 141 AggregatesAggregates ExampleExample employee Number of employees for each department: Name Department Salary

DES-Datalog> group_by(employee(N,D,S), anderson accounting 1200 [D], R=count) andrews accounting 1200 arlingon accounting 1000 Info: Processing: answer(D,R) :- nolan null null group_by(employee(N,D,S),[D],R = count). norton null null { randall resources 800 answer(accounting,3), answer(null,2), sanders sales null answer(resources,1), silver sales 1000 answer(sales,5) } smith sales 1000 Info: 4 tuples computed. Steel sales 1020

11 counts Sullivan sales null

9/21/2011 PROMETIDOS-CM Summer School 11 tuples 94 / 141 AggregatesAggregates ExampleExample ((contdcontd.).) employee

Name Department Salary Active employees (those with assigned salaries): anderson accounting 1200 DES-Datalog> group_by(employee(N,D,S), andrews accounting 1200 [D], C=count(S)) arlingon accounting 1000

nolan null null Info: Processing: answer(D,C) :- norton null null group_by(employee(N,D,S),[D],C = count(S)). randall resources 800 { answer(accounting,3), sanders sales null answer(null,0), silver sales 1000 answer(resources,1), answer(sales,3) smith sales 1000 } Steel sales 1020 Info: 4 tuples computed. Sullivan sales null 7 counts ! 9/21/2011 PROMETIDOS-CM Summer School Still, 11 tuples 95 / 141 AggregatesAggregates ExampleExample ((contdcontd.).) employee Active employees of departments with more than one active employee: Name Department Salary

anderson accounting 1200

DES-Datalog> group_by(employee(N,D,S), andrews accounting 1200 [D], arlingon accounting 1000 count(S)>1) nolan null null

Info: Processing: norton null null answer(D) :- group_by(employee(N,D,S), randall resources 800 [D], sanders sales null (A = count(S),A > 1)). { silver sales 1000 answer(accounting), smith sales 1000 answer(sales) } Steel sales 1020 Info: 2 tuples computed. Sullivan sales null

9/21/2011 PROMETIDOS-CM Summer School 96 / 141 AggregatesAggregates

AggregateAggregate metapredicatesmetapredicates:: count(Rel) count(Rel,Var) min(Rel,Var) max(Rel,Var) sum(Rel,Var) avg(Rel,Var) times(Rel,Var)

9/21/2011 PROMETIDOS-CM Summer School 97 / 141 AggregatesAggregates PredicatesPredicates andand GroupGroup ByBy

Number of employees for each department. Recall predicate group_by and functions:

DES-Datalog> group_by(employee(N,D,S), [D], C=count)

With aggregate predicates:

DES-Datalog> c(D,C) :- count(employee(N,D,S),S,C) Info: Processing: c(D,C) :- count(employee(N,D,S),S,[D],C). { c(accounting,3), c(null,0), c(resources,1), c(sales,3) } Info: 4 tuples computed.

9/21/2011 PROMETIDOS-CM Summer School 98 / 141 AggregatesAggregates andand RecursionRecursion

% SQL Program % Datalog Program

CREATE OR REPLACE VIEW path(X,Y,1) :- shortest_paths(Origin,Destination,Length) AS edge(X,Y). WITH RECURSIVE path(X,Y,L) :- path(Origin,Destination,Length) AS path(X,Z,L0), (SELECT edge.*,1 FROM edge) edge(Z,Y), UNION count(edge(A,B),Max), (SELECT L0

% SQL Query % Datalog Query: SELECT * FROM shortest_paths; shortest_paths(X,Y,L) :- min(path(X,Y,Z),Z,L).

9/21/2011 PROMETIDOS-CM Summer School 99 / 141 SafetySafety andand AggregatesAggregates

SetSet variablesvariables inin aggregateaggregate metapredicatesmetapredicates areare notnot boundbound

group_by(t(X,Y),[X],C=count)

Unsafe goal:

group_by(t(X,Y),[X],C=count), s(Y)

DES-Datalog> group_by(t(X,Y),[X],C=count), s(Y) Error: Incorrect use of shared set variables in metapredicate: [Y] DES-Datalog> /safe on DES-Datalog> group_by(t(X,Y),[X],C=count), s(Y) Info: Processing: answer(X,Y,C) :- s(Y), group_by(t(X,Y),[X],C = count).

9/21/2011 PROMETIDOS-CM Summer School 100 / 141 AggregatesAggregates andand DISTINCTDISTINCT

ForFor discardingdiscarding duplicatesduplicates (functions(functions andand metapredicatesmetapredicates):): sum_distinct count_distinct - SELECT DISTINCT COUNT(*) count_distinct(V) - SELECT COUNT(DISTINCT C) avg_distinct times_distinct No need for min_distinct and max_distinct

9/21/2011 PROMETIDOS-CM Summer School 101 / 141 WhatWhat OuterOuter JoinsJoins areare AllAll AboutAbout students name subject mark CREATE TABLE students( anderson programming 6 name string, subject string, mark int); andrews databases 5

:-type(students(name:string, arlingon databases 3 subject:string, mark:int)). arlingon programming 7

norton databases 6

smith databases NULL SELECT name FROM students answer WHERE subject='databases' AND mark >= 5 name andrews students(Name,databases,_Mark), _Mark>=5 norton

9/21/2011 PROMETIDOS-CM Summer School 102 / 141 conversion CREATE TABLE conversion(mark mark grade INT, grade STRING) ......

3 D :-type(conversion( mark:int, grade:string)) 4 D+ 5 C

6 C+ SELECT name,mark,grade ...... FROM students AS s, conversion AS c WHERE answer s.subject='databases' name mark grade

AND s.mark=c.mark andrews 5 C

arlingon 3 D students(Name,databases,Mark), conversion(Mark,Grade) norton 6 C+

9/21/2011 PROMETIDOS-CM Summer School 103 / 141 students Now,Now, wewe recallrecall aa name subject mark databasedatabase studentstudent anderson programming 6 namednamed SmithSmith andrews databases 5 arlingon databases 3 Where'sWhere's SmithSmith inin thethe answer?answer? arlingon programming 7 norton databases 6

smith databases NULL SELECT name,mark,grade FROM students AS s LEFT OUTER JOIN answer conversion AS c name mark grade ON s.mark=c.mark ON s.mark=c.mark andrews 5 C WHERE s.subject='databases' arlingon 3 D lj(students(Name,databases,SMark), norton 6 C+ conversion(CMark,Grade), SMark=CMark) smith NULL NULL

9/21/2011 PROMETIDOS-CM Summer School 104 / 141 students But,But, bewarebeware ...... name subject mark anderson programming 6

andrews databases 5 SELECTSELECT namename arlingon databases 3 FROMFROM studentsstudents arlingon programming 7 WHEREWHERE norton databases 6 subject='databases'subject='databases' smith databases NULL andand markmark >=>= 55

answer SELECTSELECT namename name FROMFROM studentsstudents andrews WHEREWHERE norton subject='databases'subject='databases' andand markmark << 55 9/21/2011 PROMETIDOS-CM Summer School 105 / 141 students name subject mark AndAnd eveneven worserworser ...... anderson programming 6 andrews databases 5

SELECTSELECT ** arlingon databases 3 FROMFROM studentsstudents arlingon programming 7 WHEREWHERE markmark ININ norton databases 6 (SELECT(SELECT markmark smith databases NULL answer FROMFROM students);students); name subject mark

anderson programming 6 Where'sWhere's damneddamned SmithSmith inin thethe answer?answer? andrews databases 5 Hasn'tHasn't SmithSmith thethe samesame arlingon databases 3 markmark asas itselfitself eventually,eventually, arlingon programming 7 eveneven ifif itit isis unknownunknown yet?yet? norton databases 6

9/21/2011 PROMETIDOS-CM Summer School 106 / 141 NullNull Semantics:Semantics: SQLSQL

ComparisonComparison Cte.Cte.1 NULLNULL LeftLeft OperatorOperator ArgumentArgument

Cte.Cte.2 True/FalseTrue/False FalseFalse OKOK ?? NULLNULL FalseFalse FalseFalse ?? ?? RightRight IncompleteIncomplete 3VL3VL ArgumentArgument a=aa=a isis FalseFalse forfor NULLNULL FalseFalse →→ UnknownUnknown 9/21/2011 PROMETIDOS-CM Summer School 107 / 141 NullNull Semantics:Semantics: DESDES

Comparison Cte.1 NULL1 NULL2 Left Operator Argument

Cte.2 True/False False False OK ? ?

NULL1 False True/False False ? OK ?

NULL2 False False True/False ? ? OK Right NULLNULL's's areare distinguishable:distinguishable: Argument '$'$NULL'(NULL'(IdId)) 9/21/2011 ButButPROMETIDOS-CM still,still, wewe Summer areare School inin aa 2VL2VL 108 / 141 DuplicatesDuplicates andand NULL'sNULL's

If duplicates are disabled, each NULL value is considered as the same constant for all of its occurrences in a program (as SQL) DES-Datalog> /assert p(null) DES-Datalog> /assert p(null) DES-Datalog> p(X) { p(null) } Info: 1 tuple computed.

If duplicates are enabled, each NULL value is considered as a different constant for each occurrence in a program (as SQL) DES-Datalog> /duplicates on DES-Datalog> p(X) { p(null), p(null) } Info: 2 tuples computed.

9/21/2011 PROMETIDOS-CM Summer School 109 / 141 So:So:

NULLNULL's's,, althoughalthough subjectsubject ofof semanticsemantic flaws,flaws, areare widelywidely usedused inin currentcurrent databasedatabase applicationsapplications However,However, theythey areare notnot usualusual inin deductivedeductive databasesdatabases (perhaps(perhaps toto above?)above?) SPARQLSPARQL (recursion(recursion isis notnot supported)supported) XSBXSB (no(no nativenative support)support) 4QL4QL (released(released inin 20112011 asas aa prototype)prototype)

9/21/2011 PROMETIDOS-CM Summer School 110 / 141 OuterOuter JoinsJoins asas providedprovided byby DESDES

NullNull values:values: Cte.: null Functions: is_null(Var) is_not_null(Var) OuterOuter joinjoin builtbuilt--ins:ins: Left ( ): lj(Left_Rel, Right_Rel, ON_Condition) Right ( ): rj(Left_Rel, Right_Rel, ON_Condition) Full ( ): fj(Left_Rel, Right_Rel, ON_Condition)

9/21/2011 PROMETIDOS-CM Summer School 111 / 141 OuterOuter JoinJoin ExamplesExamples

SQL: SELECT * FROM a LEFT JOIN b ON x=y; Datalog: lj(a(X), b(Y), X=Y)

SQL: SELECT * FROM a LEFT JOIN b WHERE x=y; Datalog: lj(a(X), b(X), true)

SQL: SELECT * FROM a LEFT JOIN (b RIGHT JOIN c ON y=u) ON x=y; Datalog: lj(a(X), rj(b(Y), c(U,V), Y=U), X=Y)

9/21/2011 PROMETIDOS-CM Summer School 112 / 141 SourceSource--toto--SourceSource TransformationsTransformations

RecallRecall thatthat lj(A,B,Clj(A,B,C)) isis thethe unionunion of:of: TuplesTuples fromfrom AA matchingmatching CC joinedjoined withwith BB TuplesTuples fromfrom AA notnot matchingmatching CC joinedjoined withwith NULLNULL's's

E.g.:E.g.: lj(s(X,U), t(V,Y), U>V)

s(1,4). answer(X, Y, U, V) → s(2,3). { answer(1, 4, 3, 5), t(3,5). answer(2, 3, null, null) }

9/21/2011 PROMETIDOS-CM Summer School 113 / 141 SourceSource--toto--SourceSource TransformationsTransformations

v(X,Y) :- lj(s(X,U),t(V,Y),U>V).

v(X,Y) :- lj('$p0'(X,U,V,Y)).

'$p0'(A,B,C,D) :- '$p1'(A,B,C,D). '$p0'(A,B,'$NULL'(C),'$NULL'(D)) :- s(A,B), not('$p1'(A,B,E,F)).

'$p1'(A,B,C,D) :- s(A,B), t(C,D), B > C. 9/21/2011 PROMETIDOS-CM Summer School 114 / 141 SourceSource--toto--SourceSource TransformationsTransformations

But,But, wewe getget anan unsafeunsafe rulerule becausebecause ofof flounderingfloundering::

'$p0'(A,B,'$NULL'(C),'$NULL'(D))

However,However, suchsuch NULLNULL specificationsspecifications areare otherwiseotherwise treatedtreated inin DESDES asas nullnull providersproviders AA nullnull providerprovider returnsreturns aa uniqueunique identifieridentifier forfor aa givengiven tupletuple ofof groundground valuesvalues

9/21/2011 PROMETIDOS-CM Summer School 115 / 141 SourceSource--toto--SourceSource TransformationsTransformations

'$p0'(A,B,'$NULL'(C),'$NULL'(D)) :- s(1,4). s(A,B), s(2,3). not('$p1'(A,B,E,F)). t(3,5).

'$p0'(2,3,'$NULL'(1),'$NULL'(2))

'$p1'(A,B,C,D) :- s(A,B), t(C,D), B > C.

'$p1'(1,4,3,5)

9/21/2011 PROMETIDOS-CM Summer School 116 / 141 TransfersTransfers toto OtherOther SystemsSystems

TheThe transformationtransformation includesincludes aa flounderingfloundering rule,rule, asas EE andand FF areare notnot rangerange restrictedrestricted ::

'$p0'(A,B,'$NULL'(C),'$NULL'(D)) :- s(A,B), not('$p1'(A,B,E,F)).

TheThe meaningmeaning ofof not('$p1') isis unsafe,unsafe, asas itit containscontains unboundedunbounded arguments:arguments:

not('$p1'(2,3,A,B))

9/21/2011 PROMETIDOS-CM Summer School 117 / 141 TransfersTransfers toto OtherOther SystemsSystems

Usually,Usually, flounderingfloundering isis notnot allowedallowed asas inin DLVDLV However,However, somesome flounderingfloundering programsprograms cancan bebe translatedtranslated intointo nonnon--flounderingfloundering [[UllmanUllman]] ThisThis timetime wewe areare luckylucky

9/21/2011 PROMETIDOS-CM Summer School 118 / 141 Transfers:Transfers: DLVDLV v(X,Y) :- lj(s(X,U),t(V,Y),U>V).

v(X,Y) :- '$p0'(X,U,V,Y).

'$p0'(A,B,'$NULL'(C),'$NULL'(D)) :- s(A,B), not('$p1'(B)). '$p0'(A,B,C,D) :- s(A,B), t(C,D), B > C. SolvedSolved atat anan extraextra costcost '$p1'(B) :- s(A,B), t(C,D), B > C.

9/21/2011 PROMETIDOS-CM Summer School 119 / 141 TransfersTransfers toto OtherOther SystemsSystems

AnotherAnother statestate--ofof--thethe--artart systemsystem isis XSBXSB Here,Here, builtbuilt--inin sk_notsk_not/1/1 allowsallows flounderingfloundering byby programprogram transformationtransformation

9/21/2011 PROMETIDOS-CM Summer School 120 / 141 Transfers:Transfers: XSBXSB v(X,Y) :- lj(s(X,U),t(V,Y),U>V).

:- table('$p0'/4), table('$p1'/4). :- table(s/2), table(t/2). main(Vs) :- findall(v(X,Y),v(X,Y),Vs). v(X,Y) :- '$p0'(X,U,V,Y). '$p0'(A,B,'$NULL'(C),'$NULL'(D)) :- get_id(C), get_id(D), s(A,B), sk_not('$p1'(A,B,E,F)). '$p0'(A,B,C,D) :- '$p1'(A,B,C,D). '$p1'(A,B,C,D) :- s(A,B), t(C,D), B > C. :- dynamic id/1. id(0). get_id(X) :- id(X), retractall(id(X)), Y is X+1, assertz(id(Y)). 9/21/2011 PROMETIDOS-CM Summer School 121 / 141 RDBMS'sRDBMS's LimitationsLimitations

Recursion precludes: Duplicate elimination (IBM DB2, Oracle) Aggregates (IBM DB2, Oracle) Recursion forces: Explicit recursion depth (MS SQL Server) Linearity (SQL Standard) Stratification on other operators (SQL Standard) MySQL does not allow recursion at all !

9/21/2011 PROMETIDOS-CM Summer School 122 / 141 CurrentCurrent RDBMS'sRDBMS's LimitationsLimitations

Example UNION ALL is required An aggregate is not allowed in the recursive part

CREATE OR REPLACE VIEW shortest_paths(Origin,Destination,Length) AS WITH RECURSIVE path(Origin,Destination,Length) AS (SELECT edge.*,1 FROM edge) UNION (SELECT path.Origin,edge.Destination,path.Length+1 FROM path,edge WHERE path.Destination=edge.Origin and path.Length < (SELECT COUNT(*) FROM Edge) ) SELECT Origin,Destination,MIN(Length) FROM path GROUP BY Origin,Destination; 9/21/2011 PROMETIDOS-CM Summer School 123 / 141 SQLSQL RecursionRecursion asas ofof CurrentCurrent DBMS'sDBMS's

CREATE VIEW parent(parent,child) AS SELECT * FROM father UNION SELECT * FROM mother;

CREATE OR REPLACE VIEW ancestor(ancestor,descendant) AS WITH RECURSIVE rec_ancestor(ancestor,descendant) AS SELECT * FROM parent UNION SELECT parent,descendant FROM parent,rec_ancestor WHERE parent.child=rec_ancestor.ancestor SELECT * FROM rec_ancestor;

DES-SQL> SELECT * FROM ancestor WHERE ancestor='tom';

9/21/2011 PROMETIDOS-CM Summer School 124 / 141 SQLSQL SimplifiedSimplified SyntaxSyntax inin DESDES

CREATE OR REPLACE VIEW ancestor(ancestor, descendant) AS SELECT parent, child FROM parent UNION SELECT parent, descendant FROM parent, ancestor WHERE parent.child=ancestor.ancestor;

9/21/2011 PROMETIDOS-CM Summer School 125 / 141 DatalogDatalog DeclarativeDeclarative DebuggerDebugger

Motivation:Motivation: AbstractAbstract thethe solvingsolving--orientedoriented debuggingdebugging procedureprocedure Roots:Roots: [Shaphiro83],[Shaphiro83], AlgorithmicAlgorithmic ProgramProgram DebuggingDebugging SemanticsSemantics--orientedoriented cf.cf. RafaRafa talktalk

9/21/2011 PROMETIDOS-CM Summer School 126 / 141 DeclarativeDeclarative DebuggerDebugger

between(X,Z):- br(X),br(Y),br(Z),X Y. Elements having preceding values in the sequence even(nil). even(X) :- odd(Z), next(Z,X). Elements in an even position+nil

odd(Y) :- even(Z), next(Z,Y). Elements in an odd position

br_is_even :- even(X), not(next(X,Y)). Succeeds if the cardinality is even br(a). Base relation (sequence of elements) br(b).

9/21/2011 PROMETIDOS-CM Summer School 127 / 141 DeclarativeDeclarative DebuggerDebugger

between(X,Z):- br(X),br(Y),br(Z),X

odd(Y) :- even(Z), next(Z,Y). Elements in an odd position

br_is_even :- even(X), not(next(X,Y)). Succeeds if the cardinality is even br(a). Base relation (sequence of elements) br(b).

9/21/2011 PROMETIDOS-CM Summer School 128 / 141 DeclarativeDeclarative debugging:debugging: aa practicalpractical sessionsession

DES> /debug br_is_even

Debugger started ... Is br(b) = {br(b)} valid(v)/non-valid(n) [v]? v Is has_preceding(b) = {} valid(v)/non-valid(n) [v]? n Is br(X) = {br(b),br(a)} valid(v)/non-valid(n) [v]? v ! Error in relation: has_preceding/1 ! Witness query: has_preceding(b) = { }

9/21/2011 PROMETIDOS-CM Summer School 129 / 141 DeclarativeDeclarative Debugging:Debugging: SemanticSemantic GraphGraph

br_is_even = { }

next(nil, Y) = {next(nil,b)} even(X) = {even(nil)}

br(nil) = { } odd(X) = {odd(b)} Non-valid

br(Y) = {br(a), br(b)} next(b, X) = { } Unknown

has_preceding(a)= {has_preceding(a)} br(b) = {br(b)}

br(a)= {br(a)} has_preceding(b)= {}

9/21/2011 PROMETIDOS-CM Summer School 130 / 141 SQLSQL DebuggerDebugger

MotivationMotivation asas ofof DatalogDatalog DebuggerDebugger AddsAdds traversingtraversing strategiesstrategies DivideDivide && QueryQuery /debug_sql Guest order(dq) Also,Also, trustedtrusted tablestables /debug_sql Guest trust_tables(no) AndAnd trustedtrusted specifications:specifications: /debug_sql Guest trust_file(pets_trust)

9/21/2011 PROMETIDOS-CM Summer School 131 / 141 SQLSQL DebuggerDebugger

Owner( id integer primary key, DES-SQL> /debug_sql Guest name varchar(50)); Info: Outcome of view 'LessThan6': Pet( code integer primary key, { name varchar(50), specie 'LessThan6'(1), varchar(20)); 'LessThan6'(1), 'LessThan6'(2), PetOwner( id integer, code 'LessThan6'(2), integer, primary key (id,code), 'LessThan6'(3), Info: Outcome of view 'AnimalOwner':': foreign key (id) references 'LessThan6'(4) { Owner(id), foreign key (code) } references Pet(code)) AnimalOwner(1,'Kitty',cat), Input: Is this view valid? (y/n/a) [y]: y AnimalOwner(1,'Wilma',dog), Info: Outcome of view AnimalOwner(2,'Lucky',dog), AnimalOwner ''NoCommonName':': AnimalOwner(2,'Wilma',cat), LessThan6 (AnimalOwner) { AnimalOwner(3,'Oreo',cat), CatsAndDogsOwner 'NoCommonName'(1), (AnimalOwner) AnimalOwner(3,'Rocky',dog), (AnimalOwner) 'NoCommonName'(2), NoCommonName AnimalOwner(4,'Cecile',turtle), NoCommonName 'NoCommonName'(3) (CatsAndDogsOwner) AnimalOwner(4,'Chelsea',dog) } Guest (NoCommonName, } LessThan6 ) Input: Is this view valid? (y/n/a) [y]: n LessThan6 ) Input: Is this view valid? (y/n/a) [y]: y Info: Outcome of view DES-SQL> select * from Guest ''CatsAndDogsOwner':': Info: Buggy view found: CatsAndDogsOwner/2. answer(Guest.id, Guest.name) -> { { 'CatsAndDogsOwner'(1,'Wilma'), answer(1,'Mark Costas'), 'CatsAndDogsOwner'(2,'Lucky'), answer(2,'Helen Kaye'), 'CatsAndDogsOwner'(3,'Rocky') answer(3,'Robin Scott') } } Input: Is this view valid? (y/n/a) [y]: n Info: 3 tuples computed.

9/21/2011 PROMETIDOS-CM Summer School 132 / 141 DatalogDatalog TracerTracer DES-Datalog> /c negation DES-Datalog> /trace_datalog a Info: Tracing predicate 'a'. { a } Info: 1 tuple in the answer table. Info : Remaining predicates: [b/0,c/0,d/0] Input: Continue? (y/n) [y]: Info: Tracing predicate 'b'. { not(b) } Info: 1 tuple in the answer table. Info : Remaining predicates: [c/0,d/0] Input: Continue? (y/n) [y]: Info: Tracing predicate 'c'. { c } Info: 1 tuple in the answer table. Info : Remaining predicates: [d/0] Input: Continue? (y/n) [y]: Info: Tracing predicate 'd'. { } Info: No more predicates to trace. 9/21/2011 PROMETIDOS-CM Summer School 133 / 141 SQL Tracer DES-SQL> /trace_sql ancestor SQL Tracer Info: Tracing view 'ancestor'. Info: Tracing view 'mother'. { { ancestor(amy,carolIII), mother(amy,fred), ...... ancestor(tony,carolIII) mother(grace,amy) } } Info: 16 tuples in the answer table. Info: 4 tuples in the answer table. Info : Remaining views: [parent/2,father/2,mother/2] Info: No more views to trace. Input: Continue? (y/n) [y]: DES-SQL> /trace_datalog father(X,Y) Info: Tracing view 'parent'. Info: Tracing predicate 'father'. { { parent(amy,fred), father(fred,carolIII), ...... parent(tony,carolII) father(tony,carolII) } } Info: 8 tuples in the answer table. Info: 4 tuples in the answer table. Info : Remaining views: [father/2,mother/2] Info: No more predicates to trace. Input: Continue? (y/n) [y]: Info: Tracing view 'father'. { father(fred,carolIII), ... father(tony,carolII) } Info: 4 tuples in the answer table. Info : Remaining views: [mother/2] Input: Continue? (y/n) [y]: 9/21/2011 PROMETIDOS-CM Summer School 134 / 141 SQLSQL TestTest CaseCase GeneratorGenerator

ProvidesProvides tuplestuples thatthat cancan bebe matchedmatched toto thethe intendedintended interpretationinterpretation ofof aa viewview TestTest casescases Positive (PTC) Negative (NTC) QueryingQuerying aa viewview w.r.tw.r.t.. PTC: One tuple, at least NTC: One tuple, at least, which does not match the WHERE condition PredicatePredicate coverage:coverage: PNTC: Contains both PTC and NTC tuples

9/21/2011 PROMETIDOS-CM Summer School 135 / 141 SQLSQL TestTest CaseCase GeneratorGenerator

PNTCPNTC DES-SQL> create table t(a int primary key) DES-SQL> create view v(a) as select a from t where a=5 DES-SQL> /test_case v Info: Test case over integers: [t(5),t(-5)] NoNo PNTCPNTC create view v(a) as select a from t where a=1 and not exists (select a from t where a<>1); SupportSupport for:for: Aggregates UNION Options: Adding/replacing results to a table Kind of generated test case (PTC, NTC, PNTC) Test case size 9/21/2011 PROMETIDOS-CM Summer School 136 / 141 SeveralSeveral otherother FeaturesFeatures ofof DESDES

TablingTabling withwith supportsupport forfor relationalrelational featuresfeatures Preprocessor:Preprocessor: Source-to-source program transformation for safety and performance Program analysis for safety DevelopmentDevelopment modemode BatchBatch processingprocessing AA widewide setset ofof commandscommands (>70)(>70) TextualTextual APIAPI forfor communicatingcommunicating toto externalexternal applicationsapplications

9/21/2011 PROMETIDOS-CM Summer School 137 / 141 ConclusionsConclusions

RelationalRelational vs.vs. DeductiveDeductive databases:databases: FOLFOL isis notnot enoughenough SQL:SQL: Syntax oriented to human speech Many functionalities Datalog:Datalog: Syntax oriented to formulas Neater formulations New needs coming from Semantic Web, Ontologies, ... But,But, syntaxsyntax isis notnot all,all, aa practicalpractical systemsystem isis thethe keykey

9/21/2011 PROMETIDOS-CM Summer School 138 / 141 Conclusions.Conclusions. DESDES

SuccessfulSuccessful implementationimplementation guidedguided byby needneed WidelyWidely used,used, bothboth forfor teachingteaching andand researchresearch NotNot reallyreally novelnovel forfor eacheach featurefeature butbut asas aa wholewhole DatalogDatalog andand SQLSQL integrationintegration Interactive,Interactive, useruser--friendly,friendly, multiplatformmultiplatform systemsystem JustJust downloaddownload itit andand play!play! NeverthelessNevertheless thethe aforementionedaforementioned novelnovel featuresfeatures Still,Still, manymany thingsthings toto dodo……

9/21/2011 PROMETIDOS-CM Summer School 139 / 141 LimitationsLimitations ((FutureFuture WorkWork))

DataData areare constants,constants, nono termsterms (functions)(functions) areare allowedallowed DatalogDatalog databasedatabase updatesupdates BeyondBeyond 2.5VL2.5VL SQLSQL coveragecoverage stillstill incompleteincomplete PrecisePrecise syntaxsyntax errorerror reportsreports SingleSingle--lineline inputsinputs ConstraintsConstraints ((àà lala CLP)CLP) PerformancePerformance …… onlyonly toto namename aa few!few!

9/21/2011 PROMETIDOS-CM Summer School 140 / 141 Canada University of California, at Los Angeles Efficient Integrity Checking for Databases with Recursive CS240A: Databases and Knowledge Bases Views Davide Martinenghi and Henning Christiansen The University of Arizona In Advances in Databases and Information Systems: 9th CsC372 East European Conference, ADBIS 2005, Tallinn, Estonia, The State University of New York September 12-15, 2005 : Proceedings Autor Johann Eder, Hele-Mai Haav, AhtoDESDESKalja, Jaan FactsFactsUniversity at Buffalo Penjam CSE 636: Data Integration ISBN 3540285857, 9783540285854 The University of British Columbia PhD CS304: Introduction to Relational Databases Science and Engineering Department University of Nebraska - Lincoln, USA Datalog Tutorial PhD Master's of in University of Texas at San Antonio, USA Arkansas Tech University, Russellville Industry: The University of Texas at Austin XLOG Technologies GmbH, Zürich CS2 CaseLab : Applied Operations Research Ideacube Australia: Links to DES: INFO2820: Database Systems 1 (Advanced) (2010 - ACM SIGMOD Online Publicly Available Database Semester 1) Software from Nonprofit Organizations Engineering and Information Technologies The ALP Newsletter. vol. 21 n. 1 The University of Sydney Datalog Wikipedia German Tab “Resources” Datalog Wikipedia English INFO2120/2820: Database Systems 1 (2009 - Semester 1) Wapedia School of Information Technologies SWI-Prolog. Related Web Resources The University of Sydney SICStus Prolog. Third Party Software. Other Research Systems Tutorial 3 SOFTPEDIA. Datalog Educational System 1.7.0 Allan Hancock College >> INFO >> 2120 Fall, 2009 Famouswhy Description: School of Information Technologies DBpedia INFO2120/2820: Database Systems I 1.Sem./2009 BDD-Based Deductive DataBase (bddbddb) Tutorial 3: SQL and Relational Algebra 23.03.2009 Other implementations of Datalog/Prolog Reach Information Africa: Ask a Word Faculty of Sciences and Technologies of Acronym finder Mohammedia (FSTM) - Morocco 9/21/2011Acronym Geek PROMETIDOS-CM Summer School 141 / 141 .