Sunteți pe pagina 1din 234

Fernando Senz-Prez 1/234

Univeisidad ConpIulense de Madiid



DalaIog LducalionaI Syslen







Datalog Educational
System V3.4
Users Manual









Ieinando Senz Ieiez
Ciupo de Iiogianacin DecIaialiva (CID)
Depailanenlo de Ingenieia deI Soflvaie e InleIigencia AilificiaI (DISIA)
Univeisidad ConpIulense de Madiid (UCM)
Decenlei, 18lh, 2O13



Fernando Senz-Prez 2/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen































Copyiighl (C) 2OO4-2O13 Ieinando Senz-Ieiez
Ieinission is gianled lo copy, disliilule and/oi nodify lhis docunenl undei lhe leins of lhe CNU Iiee
Docunenlalion License, Veision 1.3 oi any Ialei veision pulIished ly lhe Iiee Soflvaie Ioundalion, vilh
no Invaiianl Seclions, no Iionl-Covei Texls, and no ack-Covei Texls.
A copy of lhe Iicense is incIuded in Appendix A, in lhe seclion enlilIed "Documentation License".


Fernando Senz-Prez 3/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Contents

1. Introduction........................................................................................................................... 8
1.1 Deduclive Dalalases .................................................................................................. 9
2. Installation.............................................................................................................................
2.1 DovnIoading DLS ...................................................................................................... 9
2.1.1 Souice Disliilulion.............................................................................................. 9
2.1.2 LxeculalIe Disliilulion..................................................................................... 1O
2.1.2.1 Windovs ..................................................................................................... 1O
2.1.2.2 DLS+ACIDL undIe.................................................................................. 11
2.1.2.3 Linux............................................................................................................ 12
2.1.2.4 Mac OS X..................................................................................................... 13
2.2 InslaIIing and Lxeculing DLS.................................................................................. 15
2.2.1 MS Windovs....................................................................................................... 15
2.2.1.1 LxeculalIe Disliilulion............................................................................. 15
2.2.1.2 Souice Disliilulion.................................................................................... 15
2.2.2 Linux .................................................................................................................... 15
2.2.2.1 LxeculalIe Disliilulion............................................................................. 15
2.2.2.2 Souice Disliilulion.................................................................................... 15
2.2.3 Slailing DLS fion a IioIog inleipielei........................................................... 16
3. !etting Started.................................................................................................................... 1"
3.1 DalaIog Mode............................................................................................................ 17
3.2 SQL Mode .................................................................................................................. 2O
3.3 ReIalionaI AIgelia Mode......................................................................................... 23
3.4 IioIog Mode .............................................................................................................. 27
3.5 Caveals ....................................................................................................................... 27
3.6 Celling HeIp.............................................................................................................. 28
4. #uery $anguages................................................................................................................ 28
4.1 DalaIog ....................................................................................................................... 29
4.1.1 Synlax................................................................................................................... 3O
4.1.2 RuIes..................................................................................................................... 32
4.1.3 Iiogians ............................................................................................................. 32
4.1.4 Queiies................................................................................................................. 32
4.1.5 Tenpoiaiy Vievs............................................................................................... 35
4.1.6 Aulonalic Tenpoiaiy Vievs ........................................................................... 35
4.1.7 Undeiscoied VaiialIes ...................................................................................... 36
4.1.8 Negalion.............................................................................................................. 37
4.1.9 DupIicales............................................................................................................ 39
4.1.1O NuII VaIues.......................................................................................................... 42
4.1.11 Oulei }oins........................................................................................................... 43
4.1.12 Aggiegales .......................................................................................................... 45
4.1.12.1 Aggiegale Iunclions ................................................................................. 45
4.1.12.2 Cioup_ly Iiedicale................................................................................... 45
4.1.12.3 Aggiegale Iiedicales................................................................................. 48
4.1.12.4 Aggiegales and DupIicales....................................................................... 5O
4.1.13 Disjunclive odies.............................................................................................. 51
4.1.14 ReIalionaI Division in DalaIog ......................................................................... 51
4.1.15 Inlegiily Consliainls.......................................................................................... 53
4.1.15.1 Type ............................................................................................................. 53


Fernando Senz-Prez 4/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.1.15.1.1 Types on InlensionaI Dalalase......................................................... 55
4.1.15.1.2 Types on IioposilionaI ReIalions..................................................... 56
4.1.15.2 NuIIaliIily (Lxislency Consliainl)........................................................... 56
4.1.15.3 Iiinaiy Key................................................................................................ 56
4.1.15.4 Candidale Key (Uniqueness Consliainl)................................................ 57
4.1.15.5 Ioieign Key................................................................................................. 57
4.1.15.6 IunclionaI Dependency............................................................................ 59
4.1.15.7 Usei-defined Inlegiily Consliainls ......................................................... 6O
4.1.15.8 Diopping Consliainls................................................................................ 63
4.1.15.9 Caveals ........................................................................................................ 63
4.1.16 HypolhelicaI Queiies......................................................................................... 64
4.1.16.1 HypolhelicaI Queiies and Inlegiily Consliainls................................... 66
4.1.16.2 HypolhelicaI Queiies and DupIicales..................................................... 68
4.1.16.3 HypolhelicaI Queiies and Negalion ....................................................... 69
4.2 SQL.............................................................................................................................. 7O
4.2.1 Main Linilalions ................................................................................................ 7O
4.2.2 Main Iealuies ..................................................................................................... 71
4.2.3 DalaIog vs. SQL.................................................................................................. 71
4.2.4 Dala Definilion Language................................................................................. 72
4.2.4.1 Ciealing TalIes........................................................................................... 72
4.2.4.2 Ciealing Vievs........................................................................................... 74
4.2.4.3 Diopping TalIes......................................................................................... 75
4.2.4.4 Diopping Vievs......................................................................................... 76
4.2.4.5 Renaning TalIes........................................................................................ 76
4.2.4.6 Renaning Vievs ........................................................................................ 76
4.2.4.7 Diopping Dalalases .................................................................................. 76
4.2.5 Dala ManipuIalion Language........................................................................... 76
4.2.5.1 Inseiling TupIes ......................................................................................... 77
4.2.5.2 DeIeling TupIes .......................................................................................... 78
4.2.6 Dala Queiy Language........................................................................................ 78
4.2.6.1 asic SQL Queiies...................................................................................... 78
4.2.6.1.1 Top-N Queiies....................................................................................... 81
4.2.6.1.2 The dual lalIe ...................................................................................... 81
4.2.6.2 ReIalionaI Division in SQL ....................................................................... 82
4.2.6.3 Sel SQL Queiies.......................................................................................... 82
4.2.6.4 WITH SQL Queiies ..................................................................................... 83
4.2.6.5 HypolhelicaI SQL Queiies........................................................................ 84
4.2.7 Infoinalion Schena Language (ISL)............................................................... 87
4.2.8 SQL Ciannai..................................................................................................... 87
4.3 (Lxlended) ReIalionaI AIgelia................................................................................ 94
4.3.1 Opeialois............................................................................................................. 94
4.3.1.1 asic opeialois ........................................................................................... 94
4.3.1.2 AddilionaI opeialois ................................................................................. 96
4.3.1.3 Lxlended opeialois.................................................................................... 96
4.3.2 Recuision in RA.................................................................................................. 98
4.3.3 RA Ciannai....................................................................................................... 98
4.4 IioIog........................................................................................................................ 1OO
4.5 uiIl-ins .................................................................................................................... 1OO
4.5.1 Conpaiison Opeialois.................................................................................... 1O1


Fernando Senz-Prez 5/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.5.2 DalaIog and IioIog Aiilhnelic ...................................................................... 1O1
4.5.3 SQL Aiilhnelic................................................................................................. 1O3
4.5.4 Aiilhnelic uiIl-ins.......................................................................................... 1O3
4.5.4.1 Aiilhnelic Opeialois .............................................................................. 1O3
4.5.4.2 Aiilhnelic Conslanls............................................................................... 1O4
4.5.4.3 Aiilhnelic Iunclions............................................................................... 1O4
4.5.5 Negalion............................................................................................................ 1O5
4.5.6 DalaIog Oulei }oins.......................................................................................... 1O5
4.5.7 DalaIog Aggiegales.......................................................................................... 1O5
4.5.7.1 Aggiegale Iunclions ............................................................................... 1O5
4.5.7.2 Cioup_ly Iiedicale................................................................................. 1O6
4.5.7.3 Aggiegale Iiedicales............................................................................... 1O6
4.5.8 DalaIog NuII-ieIaled Iiedicales..................................................................... 1O6
4.5.9 DupIicales.......................................................................................................... 1O7
4.5.1O Top-N Queiies .................................................................................................. 1O7
%. System Descri&tion.......................................................................................................... 1'(
5.1 RDMS conneclions via ODC ............................................................................ 1O7
5.1.1 Opening an ODC Conneclion...................................................................... 1O8
5.1.2 Using a Conneclion.......................................................................................... 1O8
5.1.3 Opening SeveiaI Conneclions ........................................................................ 111
5.1.4 Cuiienl Conneclion ......................................................................................... 112
5.1.5 Making a Conneclion lhe Cuiienl One......................................................... 112
5.1.6 CIosing a Conneclion....................................................................................... 112
5.1.7 Schena and Dala VisiliIily............................................................................. 112
5.1.8 SoIving Lngine and ODC conneclions........................................................ 113
5.1.9 Inlegiily Consliainls, ODC Conneclions, and Ieisislency...................... 114
5.1.1O Caveals and Linilalions.................................................................................. 116
5.1.1O.1 Caching...................................................................................................... 116
5.1.1O.2 ODC Meladala....................................................................................... 117
5.1.1O.3 ODC Linilalions.................................................................................... 117
5.1.1O.4 IIalfoin-specific Issues........................................................................... 117
5.1.11 Tesled ODC Diiveis ...................................................................................... 118
5.2 Ieisislency ............................................................................................................... 118
5.2.1 Ieisisling a Iiedicale....................................................................................... 118
5.2.2 Using Ieisislenl Iiedicales............................................................................. 119
5.2.3 Iiocessing a Ieisislency Asseilion................................................................ 12O
5.2.4 Resloiing Iiedicales ........................................................................................ 121
5.2.5 Schena of Ieisislenl Iiedicales ..................................................................... 122
5.2.6 Renoving Iiedicale Ieisislency.................................................................... 124
5.2.7 Schena and Dala VisiliIily............................................................................. 125
5.2.8 AppIicalions...................................................................................................... 127
5.2.9 Caveals............................................................................................................... 129
5.2.9.1 InconpIele Meanings .............................................................................. 129
5.2.9.2 Opening and CIosing Conneclions........................................................ 13O
5.2.9.3 AloIishing Iiedicales.............................................................................. 13O
5.2.9.4 NuII VaIues ............................................................................................... 13O
5.2.9.5 LxleinaI Dalalase Iiocessing ................................................................ 13O
5.2.9.6 Suppoiled IIalfoins ............................................................................... 13O
5.3 Safely and ConpulaliIily...................................................................................... 13O
5.3.1 CIassicaI Safely ................................................................................................. 13O


Fernando Senz-Prez 6/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

5.3.2 Safely foi Aggiegales and DupIicale LIininalion....................................... 134
5.4 Modes foi Unsafe Iiedicales................................................................................. 135
5.5 Souice-lo-Souice Tiansfoinalions....................................................................... 136
5.6 MuIli-Iine Mode ...................................................................................................... 136
5.7 DeveIopnenl Mode................................................................................................ 137
5.8 DalaIog and SQL Tiaceis....................................................................................... 14O
5.8.1 Tiacing DalaIog Queiies ................................................................................. 14O
5.8.2 Tiacing SQL Vievs........................................................................................... 141
5.9 DalaIog DecIaialive Deluggei.............................................................................. 142
5.1O SQL DecIaialive Deluggei.................................................................................... 144
5.1O.1 Tiusled Specificalions...................................................................................... 146
5.1O.2 Missing and Wiong TupIes............................................................................. 147
5.1O.2.1 Missing TupIes ......................................................................................... 147
5.1O.2.2 Wiong TupIes........................................................................................... 149
5.1O.2.3 DispIaying Lxlended Infoinalion......................................................... 149
5.11 SQL Tesl Case Ceneialoi ....................................................................................... 15O
5.12 alch Iiocessing...................................................................................................... 151
5.13 Messages .................................................................................................................. 152
5.14 Connands............................................................................................................... 153
5.14.1 DLS Dalalase.................................................................................................... 154
5.14.2 ODC Dalalase................................................................................................ 156
5.14.3 Delugging and Tesl Case Ceneialion........................................................... 157
5.14.4 TalIing............................................................................................................... 158
5.14.5 Opeialing Syslen............................................................................................. 158
5.14.6 Log...................................................................................................................... 159
5.14.7 Infoinalive........................................................................................................ 159
5.14.8 Queiy Languages ............................................................................................. 163
5.14.9 TAII-ieIaled...................................................................................................... 164
5.14.1O MisceIIanea ............................................................................................... 164
5.14.11 InpIenenloi ............................................................................................. 166
5.14.11.1 Syslen vaiialIes .................................................................................. 167
5.15 TexluaI AII .............................................................................................................. 17O
5.15.1 Noles aloul lhe Inleiface ................................................................................ 171
5.15.1.1 Idenlifieis .................................................................................................. 171
5.15.1.2 Kinds of Ansveis..................................................................................... 172
5.15.2 TAII-enalIed Connands............................................................................... 172
5.15.3 TAII-enalIed Queiies ..................................................................................... 181
5.16 ISO Lscape Chaiaclei Synlax ................................................................................ 183
5.17 Noles aloul lhe InpIenenlalion of DLS............................................................. 184
5.17.1 TalIing............................................................................................................... 185
5.17.2 Iixpoinl Conpulalion ..................................................................................... 186
5.17.3 Dependency Ciaphs and Slialificalion: Negalion, Oulei }oins, and
Aggiegales ........................................................................................................ 187
5.17.4 Oplinizalions ................................................................................................... 187
5.17.4.1 ConpIele Conpulalions (/optimize_cc) ........................................ 188
5.17.4.2 LxlensionaI Iiedicales (/optimize_ep) ............................................ 19O
5.17.4.4 Non-iecuisive Iiedicales (/optimize_nrp) ..................................... 191
5.17.4.5 Slialun (/optimize_st)...................................................................... 192
5.17.5 Indexing (/indexing).................................................................................... 193


Fernando Senz-Prez 7/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

5.17.6 Ioiling lo Unsuppoiled Syslens................................................................... 194
". E)am&les............................................................................................................................ 14
6.1 ReIalionaI Opeialions (fiIes relop.{dl,sql,ra}) ........................................ 195
6.2 Ialhs in a Ciaph (fiIes paths.{dl,sql,ra}) ................................................. 198
6.3 Shoilesl Ialhs (fiIe spaths.{dl,sql,ra}) ..................................................... 199
6.4 IaniIy Tiee (fiIes family.{dl,sql,ra}) ....................................................... 2O1
6.5 asic Recuision IiolIen (fiIe recursion.dl)................................................. 2O3
6.6 Tiansilive CIosuie (fiIes tranclosure.{dl,sql,ra})................................ 2O3
6.7 MuluaI Recuision (fiIes mutrecursion.{dl,sql,ra}) .............................. 2O4
6.8 Iainei-WoIf-Coal-Callage IuzzIe (fiIe puzzle.dl) ..................................... 2O5
6.8.1 DeaIing vilh palhs (fiIe puzzle1.dl)......................................................... 2O7
6.9 Iaiadoxes (fiIes russell.{dl,sql,ra})........................................................ 2O9
6.1O Iaiily (fiIe parity.dl)......................................................................................... 211
6.11 Ciannai (fiIe grammar.dl) ................................................................................ 212
6.12 Iilonacci (fiIe fib.{dl,sql,ra}) .................................................................... 213
6.13 Hanoi Toveis (fiIe hanoi.dl)............................................................................. 214
6.14 Olhei LxanpIes....................................................................................................... 215
(. Contri*utions.................................................................................................................... 21%
8. +elated ,or- .................................................................................................................... 21"
8.1 Deduclive Dalalase Syslens ................................................................................ 216
8.2 TechnoIogicaI Tiansfeis ......................................................................................... 218
. .uture En/ancements...................................................................................................... 218
1'. Ca0eats and $imitations.................................................................................................. 218
11. +elease 1otes.................................................................................................................... 21
11.1 Veision 3.4 of DLS (ieIeased on Decenlei, 18lh, 2O13) .................................... 219
12. 2c-no3ledgements ......................................................................................................... 221
2&&endi) 2. $icense....................................................................................................... 223
4i*liogra&/y........................................................................................................................... 231



Fernando Senz-Prez 8/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


1. Introduction
The DalaIog LducalionaI Syslen (DLS) is a fiee, open-souice, nuIlipIalfoin,
poilalIe, IioIog-lased inpIenenlalion of a deduclive dalalase syslen. DLS 3.4 is lhe
cuiienl inpIenenlalion, vhich enjoys DalaIog, ReIalionaI AIgelia and SQL queiy
Ianguages, fuII iecuisive evaIualion vilh nenoizalion lechniques, fuII-fIedged
aiilhnelic, slialified negalion, dupIicales and dupIicale eIininalion, inlegiily
consliainls, ODC conneclions lo exleinaI ieIalionaI dalalase nanagenenl syslens
(RDMSs), DalaIog and SQL liaceis, a lexluaI AII foi exleinaI appIicalions, and noveI
appioaches lo hypolhelicaI SQL queiies and DalaIog iuIes, decIaialive delugging of
DalaIog queiies and SQL vievs, lesl case geneialion foi SQL vievs, nodes, nuII vaIues
suppoil, (lalIed) oulei join and aggiegale piedicales. The syslen is inpIenenled on
lop of IioIog and il can le used fion a IioIog inleipielei iunning on any OS
suppoiled ly such inleipielei. Moieovei, Windovs, Linux and MacOSX execulalIes
aie aIso piovided.
We have deveIoped DLS aining lo have a sinpIe, inleiaclive, nuIlipIalfoin,
and affoidalIe syslen (nol necessaiiIy efficienl) foi sludenls, so lhal lhey can gel lhe
fundanenlaI concepls lehind a deduclive dalalase vilh DalaIog, ReIalionaI AIgielia
and SQL as queiy Ianguages. SQL is suppoiled vilh a ieasonalIe coveiage of lhe
slandaid foi leaching puiposes. Suppoiled (exlended) ieIalionaI aIgelia incIudes
dupIicales, oulei joins and iecuision. Olhei deduclive syslens aie nol fuIIy suiled lo
oui needs due lo lhe alsence of sone chaiacleiislics DLS does offei foi oui educalionaI
puiposes. This syslen is nol laigeled as a conpIele deduclive dalalase, so lhal il does
nol piovide liansaclions, secuiily, and olhei fealuies piesenl in cuiienl dalalase
syslens.
The nain noveIly of lhe cuiienl ieIease is lhe ACIDL lundIe vhich incIudes a
nev veision O.12 fealuiing a IDC paneI foi dispIaying lhe piedicale dependency
giaph, and aIso ieIocalalIe paneIs lo ieoiganize lhe IDL Iayoul. Wilh iespecl lo DLS
ilseIf, sone enhancenenls have leen added, ieIaled lo an exlension lo RA piojeclion
and DalaIog division. AIso, noie infoinalion has leen added foi unsafe iuIes (node
infoinalion and sel vaiialIe unsafely) and SQL synlax eiiois. Changes incIude
oveiiiding lhe cuiienl ansvei oideiing vhen an oidei ly nelapiedicale oi cIause is
invoIved in lhe queiy, and dupIicale eIininalion, vhich voiks cIoseIy lo SQL
inpIenenlalions vhen invoIving nuII vaIues. The conpIele Iisl of enhancenenls,
changes and fixed lugs aie Iisled in Seclion 11.1.
A noveI conliilulion inpIenenled in lhis syslen is a decIaialive deluggei of
DalaIog queiies |CCSO7,CCSO8j, vhich ieIies on piogian senanlics ialhei lhan on lhe
conpulalion nechanisn. The delugging piocess is usuaIIy slailed vhen lhe usei
delecls an unexpecled ansvei lo a queiy. y asking queslions aloul lhe inlended
senanlics, lhe deluggei Iooks foi incoiiecl piogian ieIalions. See Seclion 5.9 foi
delaiIs. AIso, a siniIai decIaialive appioach has leen used lo inpIenenl an SQL
decIaialive deluggei, foIIoving |CCS11lj. Theie, possilIe eiioneous oljecls
coiiespond lo vievs, and lhe deluggei Iooks foi eiioneous vievs asking lhe usei
vhelhei lhe iesuIl of a given viev is as expecled. In addilion, liusled vievs aie
suppoiled lo piune lhe nunlei of queslions. This vas exlended lo aIso incIude usei
infoinalion aloul viong and nissing lupIes |CCS12aj. See Seclion 5.1O foi delaiIs. In


Fernando Senz-Prez /234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

addilion, foIIoving lhe need foi calching piogian eiiois vhen handIing Iaige anounls
of dala, ve aIso incIude a lesl case geneialoi foi SQL coiieIaled vievs |CCS1Oaj. Oui
looI can le used lo geneiale posilive, negalive and lolh posilive-negalive lesl cases (cf.
Seclion 5.11).
1.1 Deducti0e Data*ases
The inleiseclion of dalalases, Iogic, and ailificiaI inleIIigence deIiveied
deduclive dalalases. Deduclive dalalase syslens aie dalalase nanagenenl syslens
luiIl aiound a IogicaI nodeI of dala, and lheii queiy Ianguages aIIov expiessing
IogicaI queiies. ReIalionaI dalalase Ianguages (vheie SQL is lhe de-facto slandaid)
inpIenenl a Iiniled foin of Iogic vheieas deduclive dalalase Ianguages inpIenenl
advanced foins of Iogic.
A deduclive dalalase is a syslen vhich incIudes pioceduies foi defining
deduclive iuIes vhich can infei infoinalion (in lhe so-caIIed inlensionaI dalalase) in
addilion lo lhe facls Ioaded in lhe (so-caIIed exlensionaI) dalalase. The Iogic nodeI foi
deduclive dalalases is cIoseIy ieIaled lo lhe ieIalionaI nodeI and, in pailicuIai, vilh
lhe donain ieIalionaI caIcuIus. Theii queiy Ianguages aie ieIaled vilh lhe IioIog
Ianguage and, nainIy, vilh DalaIog, a IioIog sulsel vilhoul consliucled leins (in
oidei lo avoid infinile leins) and olhei non-decIaialive consliucls such as lhe cul.
Oiigins of deduclive dalalases can le found in aulonalic lheoien pioving and,
Ialei, in Iogic piogianning. Minkei |Mink87j suggesled lhal Cieen and RaphaeI
|CR68j veie lhe pioneeis in discoveiing lhe ieIalion lelveen lheoien pioving and
deduclion in dalalases. They deveIoped seveiaI queslion-ansvei syslens using a
veision of lhe Rolinson iesoIulion piincipIe |Roli65j, shoving lhal deduclion can le
syslenalicaIIy peifoined in a dalalase enviionnenl. Olhei pioneei syslens veie
MRIIS |MN82j, DLDUCL-2 |Chan78j and DADM |KT81j. See Seclion 8 foi iefeiences
lo olhei cuiienl deduclive dalalase syslens.
2. Installation
2.1 Do3nloading DES
You can dovnIoad lhe syslen fion lhe DLS vel page via lhe URL:

http://des.sourceforge.net/
Theie, you can find souice disliilulions foi seveiaI IioIog inleipieleis and
opeialing syslens, and execulalIe disliilulions foi MS Windovs, Linux and Mac OS.
2.1.1 Source Distri*ution
Undei lhe souice disliilulion, lheie aie seveiaI veisions depending on lhe
IioIog inleipielei you seIecl lo iun DLS: eilhei SICSlus IioIog |SICSlusj oi SWI-IioIog
|WieIej. Hovevei, adapling lhe code in lhe fiIe des_glue.pl, il couId le poiled lo
any olhei IioIog syslen. (See Seclion 5.17.3 foi poiling lo unsuppoiled syslens.) We
have lesled DLS undei SICSlus IioIog 4.2.3 and SWI-IioIog 6.6.1), and seveiaI
opeialing syslens (MS Windovs XI/Visla/7, Ulunlu 1O.O4.1, Ulunlu 12.O4, and
MacOSX Snov Leopaid).


Fernando Senz-Prez 1!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The souice disliilulion cones in a singIe aichive fiIe conlaining lhe foIIoving:
readmeDES50ersion6.t)t. A quick inslaIIalion guide and fiIe ieIease conlenls
des.&l. Coie of DLS, incIuding DalaIog piocessoi
des7dcg.&l. DCC expansion
des7s8l.&l. SQL piocessoi
des7ra.&l. RA piocessoi
des7s8l7de*ug.&l. SQL decIaialive deluggei
des7dl7de*ug.&l. DalaIog decIaialive deluggei
des7/el&.&l. HeIp syslen
des7commands.&l. Connands
des7modes.&l. Modes foi DalaIog piedicales and iuIes
des7ty&es.&l. Type infeiiei foi SQL, RA and DalaIog
des7tc.&l. Tesl case geneialoi foi SQL vievs
des7glue.&l. Conlains pailicuIai code foi lhe seIecled hosl IioIog syslen
doc9manualDES50ersion6.&d:. This nanuaI
e)am&les9;.dl LxanpIe fiIes vhich viII le discussed in Seclion 6
license9license A veilalin copy of lhe CNU IulIic License foi lhis disliilulion
2.1.2 E)ecuta*le Distri*ution
2.1.2.1 ,indo3s
Iion lhe sane URL alove, you can dovnIoad a Windovs execulalIe
disliilulion in a singIe aichive fiIe conlaining lhe foIIoving:
readmeDES50ersion6.t)t. A quick inslaIIalion guide and fiIe ieIease conlenls
des.e)e. ConsoIe execulalIe fiIe, inlended lo le slailed fion a OS connand sheII,
as depicled in lhe nexl figuie:


Fernando Senz-Prez 11/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


des3in.e)e. Windovs-appIicalion execulalIe fiIe, as depicled leIov:

IIease nole lhal lhe nenu lai alove is inheiiled fion lhe hosl IioIog syslen and aII ils
sellings appIy lo such syslen, nol lo DLS.
;.dll. DLL Iiliaiies foi lhe iunline syslen
doc9manualDES50ersion6.&d:. This nanuaI
e)am&les9;.dl LxanpIe fiIes vhich viII le discussed in Seclion 6
license9license A veilalin copy of lhe CNU IulIic License foi lhis disliilulion
2.1.2.2 DES<2CIDE 4undle
Iion lhe sane URL alove, you can dovnIoad a lundIe incIuding lolh DLS
and lhe inlegialed deveIopnenl enviionnenl ACIDL, pieconfiguied lo voik vilh
DLS. The foIIoving figuie is a snapshol of lhe syslen:


Fernando Senz-Prez 12/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


2.1.2.3 $inu)
Iion lhe sane URL alove, you can dovnIoad a Linux execulalIe disliilulion
in a singIe aichive fiIe conlaining lhe foIIoving:
readmeDES50ersion6. A quick inslaIIalion guide and fiIe ieIease conlenls
des. ConsoIe execulalIe fiIe
doc9manualDES50ersion6.&d:. This nanuaI
e)am&les9;.dl LxanpIe fiIes vhich viII le discussed in Seclion 6
license9license A veilalin copy of lhe CNU IulIic License foi lhis disliilulion
The foIIoving scieenshol has leen laken in Ulunlu 1O.O4.1:


Fernando Senz-Prez 13/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen



The sane Windovs ACIDL lundIe can le dovnIoaded foi Linux. The
foIIoving snapshol shovs lhis iunning on Ulunlu 1O.O4:

2.1.2.4 Mac =S >
Iion lhe sane URL alove, you can dovnIoad a Mac OS X execulalIe
disliilulion in a singIe aichive fiIe conlaining lhe foIIoving:


Fernando Senz-Prez 14/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

readmeDES50ersion6. A quick inslaIIalion guide and fiIe ieIease conlenls
des. ConsoIe execulalIe fiIe
doc9manualDES50ersion6.&d:. This nanuaI
e)am&les9;.dl LxanpIe fiIes vhich viII le discussed in Seclion 6
license9license A veilalin copy of lhe CNU IulIic License foi lhis disliilulion
The foIIoving scieenshol has leen laken in Mac OS X Snov Leopaid:

Theie is aIso an ACIDL lundIe lhal can le dovnIoaded foi MacOSX. The
foIIoving snapshol shovs lhis iunning on MacOS Snov Leopaid:



Fernando Senz-Prez 15/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

2.2 Installing and E)ecuting DES
Unpack lhe disliilulion aichive fiIe inlo lhe diiecloiy you vanl lo inslaII DLS,
vhich viII le iefeiied lo as lhe disliilulion diiecloiy fion nov on. This aIIovs you lo
iun lhe syslen, vhelhei you have a IioIog inleipielei oi nol (in lhis Iallei case, you
have lo iun lhe syslen eilhei on MS Windovs, Linux oi MacOS).
AIlhough lheie is no need foi fuilhei selup and you can go diieclIy lo Seclion
2.2.3, you can aIso configuie a noie usei-fiiendIy vay foi syslen slail. In lhis vay,
you can foIIov lvo ioules depending on lhe opeialing syslen.
2.2.1 MS ,indo3s
2.2.1.1 E)ecuta*le Distri*ution
SinpIy cieale a shoilcul in lhe desklop foi execuling lhe execulalIe of youi
choice: eilhei des.exe, oi deswin.exe oi des_acide.jar. The foinei is a consoIe-
lased execulalIe, lhe second is a vindovs-lased execulalIe, and lhe Iallei is a }ava
appIicalion lhal incIudes a caII lo lhe linaiy des.exe. LxeculalIes have leen
geneialed vilh SICSlus IioIog and SWI-IioIog, so lhal aII noles ieIaling lhese syslens
in lhe iesl of lhis docunenl aIso appIy lo lhese execulalIes. In addilion, since il is a
poilalIe appIicalion, il needs lo le slailed fion ils disliilulion diiecloiy, vhich neans
lhal lhe slail-up diiecloiy of lhe shoilcul nusl le lhe disliilulion diiecloiy.
2.2.1.2 Source Distri*ution
Ieifoin lhe foIIoving sleps:
1. Cieale a shoilcul in lhe desklop foi iunning lhe IioIog inleipielei of youi choice.
2. Modify lhe slail diiecloiy in lhe Iiopeilies diaIog lox of lhe shoilcul lo lhe
inslaIIalion diiecloiy foi DLS. This aIIovs lhe syslen lo consuIl lhe needed fiIes al
slailup.
3. Append lhe foIIoving oplions lo lhe IioIog execulalIe palh, depending on lhe
IioIog inleipielei you use:
(a) SICSlus IioIog: -l des.pl
(l) SWI-IioIog: -g "ensure_loaded(des)" (ienove --win_app if piesenl)
Anolhei aIleinalive is lo viile a lalch fiIe siniIai lo lhe sciipl fiIe desciiled in
lhe nexl seclion.
2.2.2 $inu)
2.2.2.1 E)ecuta*le Distri*ution
You can cieale a sciipl oi an aIias foi execuling lhe fiIe des al lhe disliilulion
iool. This execulalIe has leen geneialed undei SICSlus IioIog, so lhal aII SICSlus
noles in lhe iesl of lhis docunenl aIso appIy lo lhese execulalIes. In addilion, since il is
a poilalIe appIicalion, il needs lo le slailed fion ils disliilulion diiecloiy.
2.2.2.2 Source Distri*ution
You can viile a sciipl foi slailing DLS accoiding lo lhe seIecled IioIog
inleipielei, as foIIovs:
(a) SICSlus IioIog:


Fernando Senz-Prez 16/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


$SICSTUS l des.pl
Iiovided lhal $SICSTUS is lhe vaiialIe vhich hoIds lhe alsoIule fiIenane of lhe
SICSlus IioIog execulalIe.
(l) SWI-IioIog:

$SWI -g "ensure_loaded(des)"
Iiovided lhal $SWI is lhe vaiialIe vhich hoIds lhe alsoIule fiIenane of lhe SWI-
IioIog execulalIe.
2.2.3 Starting DES :rom a ?rolog inter&reter
esides lhe nelhods jusl desciiled, you can slail DLS fion a IioIog inleipielei,
disiegaiding lhe OS and pIalfoin, fiisl changing lo lhe disliilulion diiecloiy, and lhen
sulnilling:

?- [des].
Oi lellei, if lhe syslen does suppoil il:

?- ensure_loaded(des).
If lhe syslen does nol slail ly ilseIf, lhen lype:

?- start.
3. !etting Started
Whichevei nelhod you use lo slail DLS (a sciipl, lalch fiIe, oi shoilcul, as
desciiled in Seclion 2.2), you gel lhe foIIoving:
*********************************************************
* *
* DES: Datalog Educational System v.3.1 *
* *
* Type "/help" for help about commands *
* *
* Fernando Saenz-Perez (c) 2004-2013 *
* GPD UCM *
* Please send comments, questions, etc. to: *
* fernan@sip.ucm.es *
* Web site: *
* http://des.sourceforge.net/ *
* *
* This program comes with ABSOLUTELY NO WARRANTY, is *
* free software, and you are welcome to redistribute it *
* under certain conditions. Type "/license" for details *
*********************************************************

DES>

This Iasl Iine (DES>) is lhe DLS syslen pionpl, vhich aIIovs you lo viile
DalaIog, SQL and ReIalionaI AIgelia (RA) queiies, connands, lenpoiaiy vievs and


Fernando Senz-Prez 17/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

conjunclive queiies (see nexl seclions). If an eiioi Ieads lo an exil fion DLS and you
have slailed fion a IioIog inleipielei, lhen you can viile des. (without lhe doulIe
quoles and with lhe dol) al lhe IioIog pionpl lo conlinue.
AIlhough a queiy in any of lhe Ianguages alove can le sulnilled fion such
pionpl, lheie aie cuiienlIy foui nodes avaiIalIe vhich enalIe lo use a conciele queiy
inleipielei foi DalaIog, SQL, ReIalionaI AIgelia and IioIog. The fiisl one is lhe defauIl.
A node can le svilched via lhe connands /datalog, /sql, /ra and /prolog,
iespecliveIy. Nole lhal connands aIvays slail vilh a sIash (/). Anyvay, if you aie in a
given node, you can sulnil queiies oi goaIs lo olhei inleipieleis sinpIy viiling lhe
queiy oi goaI aflei any of lhe pievious connands. AIso, if you aie in DalaIog node,
you can diieclIy sulnil lolh SQL and RA queiies.
Dala aie sloied in a deduclive dalalase, incIuding facls and iuIes. AII queiies
and goaIs, iiiespeclive of lhe Ianguage, iefei lo lhis dalalase. When an exleinaI
dalalase is opened (see Seclion 5.1), lheii lalIes and vievs aie avaiIalIe and can le
queiied fion DalaIog, IioIog and SQL.
In conliasl vilh olhei inleipieleis, defauIl inpul node is singIe-Iine, vhich
neans lhal lhe inpul viII le piocessed aflei hilling lhe Inlio key, vhich aIIovs lo onil
lhe leininaling chaiaclei. NonelheIess, lhis node can le svilched lo nuIli-Iine as
desciiled in Seclion 5.6 vilh lhe connand /multiline on.
3.1 Datalog Mode
In lhis node, a queiy is senl lo lhe DalaIog piocessoi. If il does nol foIIov
DalaIog synlax, lhen il is senl, fiisl, lo lhe SQL piocessoi (see Seclion O) and, second, lo
lhe RA piocessoi (see Seclion 4.3) shouId such queiy is viillen in any of lhese olhei
queiy Ianguages (See caveals in Seclion 3.5). Connands (see Seclion 5.14) aie senl lo
lhe connand piocessoi. Connands can end vilh an oplionaI dol. In singIe-Iine node,
DalaIog inpuls can aIso end vilh an oplionaI dol, lul lhe dol is iequiied in nuIli-Iine
node. DalaIog node is lhe defauIl and can le anyvay enalIed via lhe connand
/datalog.
The lypicaI vay of using lhe syslen is lo viile DalaIog piogian fiIes (vilh
defauIl exlension .dl) and consuIling lhen lefoie sulnilling queiies. Anolhei
aIleinalive is lo asseil piogian iuIes fion lhe syslen pionpl.
IoIIoving lhe fiisl aIleinalive, you viile lhe piogian in a lexl fiIe, and lhen
change lo lhe palh vheie lhe fiIe is Iocaled ly using lhe connand /cd Path, vheie
Path is lhe nev diiecloiy (ieIalive oi alsoIule). Nexl, lhe connand /consult
FileName is used lo consuIl lhe fiIe FileName.
Iiovided lheie aie a nunlei oi exanpIe fiIes in lhe diiecloiy examples al lhe
disliilulion diiecloiy, and assuning lhal lhe cuiienl palh is lhe disliilulion diiecloiy
(as ly defauIl), one can use lhe foIIoving connands lo consuIl lhe exanpIe fiIe
relop.dl:
1


DES> /cd examples


1
See seclion 5 foi noie delaiIs aloul connands.


Fernando Senz-Prez 18/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> /consult relop.dl
Info: 18 rules consulted.
(vheie lhe defauIl exlension .dl can le onilled). Nole lhal iuIes in fiIes nusl end
vilh a dol, in conliasl lo connand pionpl inpuls, vheie lhe dol is oplionaI in singIe-
Iine inpul. RuIes in a consuIled fiIe nay span on nuIlipIe Iines.
Then, one can exanine lhe conlenls of lhe dalalase (see Seclion 6.1 foi an expIanalion
of lhe consuIled piogian) via lhe connand:

DES> /listing

a(a1).
a(a2).
a(a3).
b(a1).
b(b1).
b(b2).
c(a1,a1).
c(a1,b2).
c(a2,b2).
cartesian(X,Y) :-
a(X),
b(Y).
difference(X) :-
a(X),
not(b(X)).
full_join(X,Y) :-
fj(a(X),b(Y),X = Y).
inner_join(X) :-
a(X),
b(X).
left_join(X,Y) :-
lj(a(X),b(Y),X = Y).
projection(X) :-
c(X,Y).
right_join(X,Y) :-
rj(a(X),b(Y),X = Y).
selection(X) :-
a(X),
X = a2.
union(X) :-
a(X)
;
b(X).

Info: 18 rules listed.
Sulnilling a queiy is pielly easy:

DES> a(X)
{
a(a1),
a(a2),
a(a3)


Fernando Senz-Prez 1/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

}
Info: 3 tuples computed.
You can inleiacliveIy add nev iuIes vilh lhe connand /assert, as in:

DES> /assert a(a4)
DES> a(X)
{
a(a1),
a(a2),
a(a3),
a(a4)
}
Info: 4 tuples computed.
Saving lhe cuiienl dalalase, vhich nay incIude such inleiacliveIy added (oi
deIeled) lupIes, is aIIoved vilh lhe connand /save_ddb Filename, vhich saves in
a pIain fiIe lhe DalaIog iuIes in nenoiy. Lalei, lhey can le iesloied vilh
/restore_ddb Filename (lhis connand is onIy an aIias foi /consult.) In lhe
foIIoving session, lhe cuiienl dalalase is sloied, aloIished (cIeaied), and finaIIy
iesloied. AII lhe dala, incIuding lhe ones inleiacliveIy added have leen iecoveied:

DES> /save_ddb db.dl
DES> /abolish
DES> /restore_ddb db.dl
Info: 19 rules consulted.
DES> a(X)
{
a(a1),
a(a2),
a(a3),
a(a4)
}
Info: 4 tuples computed.
Anolhei usefuI connand is /list_et, vhich Iisls, in pailicuIai, lhe ansveis
aIieady conpuled. IoIIoving lhe Iasl seiies of queiies and connands alove, ve
sulnil:

Answers:
{
a(a1),
a(a2),
a(a3),
a(a4)
}
Info: 4 tuples in the answer table.
Calls:
{
a(A)
}
Info: 1 tuple in the call table.
Heie, ve can see lhal lhe conpuled neaning of lhe queiied ieIalion is sloied in
an exlension lalIe, as veII as lhe Iasl caII (cf. seclions 5.17.1 and 5.17.2). UnIess eilhei


Fernando Senz-Prez 2!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

lhe dalalase is changed (e.g., via /assert oi /retract connands) oi a lenpoiaiy
viev (see Seclion 4.1.6) execuled oi lhe connand /clear_et is sulnilled, lhe
exlension lalIe keeps conpuled iesuIls, olheivise il is cIeaied.
3.2 S#$ Mode
In lhis node, queiies aie senl lo lhe SQL piocessoi, vheieas connands (cf.
Seclion 5.14) aie senl lo lhe connand piocessoi. SQL queiies can end vilh an oplionaI
senicoIon in singIe-Iine node. MuIli-Iine node iequiies lhe ending senicoIon. SQL
node is enalIed via lhe connand /sql. DalaIog and RA queiies cannol le handIed
ly lhis node.
If ve vanl lo deveIop an anaIogous SQL exanpIe session lo lhe DalaIog
exanpIe in lhe Iasl seclion, ve can sulnil lhe fiisl inpuls (aIso avaiIalIe in lhe fiIe
examples/relop.sql) Iisled leIov (lhe exanpIe is augnenled lo piovide a fiisl
gIance of SQL). Nov, ansvei ieIalions lo SQL queiies aie denoled ly lhe ieIalion
nane answer. AIso nole lhal Iines slailing ly % aie sinpIy ienaiks. If you vish lo
aulonalicaIIy iepioduce lhe foIIoving inleiaclive session of inpuls, you can lype
/process examples/relop.sql (nolice lhal you nusl onil examples/ if you aie
in lhis diiecloiy aIieady):

Info: Processing file 'relop.sql' ...
DES> % Switch to SQL interpreter
DES> /sql
DES-SQL> % Creating tables
DES-SQL> create or replace table a(a string);
DES-SQL> create or replace table b(b string);
DES-SQL> create or replace table c(a string,b string);
DES-SQL> % Listing the database schema
DES-SQL> /dbschema
Info: Table(s):
* a(a:string(varchar))
* b(b:string(varchar))
* c(a:string(varchar),b:string(varchar))
Info: No views.
Info: No integrity constraints.
DES-SQL> % Inserting values into tables
DES-SQL> insert into a values ('a1');
Info: 1 tuple inserted.
DES-SQL> insert into a values ('a2');
Info: 1 tuple inserted.
DES-SQL> insert into a values ('a3');
Info: 1 tuple inserted.
DES-SQL> insert into b values ('b1');
Info: 1 tuple inserted.
DES-SQL> insert into b values ('b2');
Info: 1 tuple inserted.
DES-SQL> insert into b values ('a1');
Info: 1 tuple inserted.
DES-SQL> insert into c values ('a1','b2');
Info: 1 tuple inserted.
DES-SQL> insert into c values ('a1','a1');
Info: 1 tuple inserted.


Fernando Senz-Prez 21/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES-SQL> insert into c values ('a2','b2');
Info: 1 tuple inserted.
DES-SQL> % Testing the just inserted values
DES-SQL> select * from a;
answer(a.a) ->
{
answer(a1),
answer(a2),
answer(a3)
}
Info: 3 tuples computed.
DES-SQL> select * from b;
answer(b.b) ->
{
answer(a1),
answer(b1),
answer(b2)
}
Info: 3 tuples computed.
DES-SQL> select * from c;
answer(c.a, c.b) ->
{
answer(a1,a1),
answer(a1,b2),
answer(a2,b2)
}
Info: 3 tuples computed.
DES-SQL> % Projection
DES-SQL> select a from c;
answer(c.a) ->
{
answer(a1),
answer(a2)
}
Info: 2 tuples computed.
DES-SQL> % Selection
DES-SQL> select a from a where a='a2';
answer(a.a) ->
{
answer(a2)
}
Info: 1 tuple computed.
DES-SQL> % Cartesian product
DES-SQL> select * from a,b;
answer(a.a, b.b) ->
{
answer(a1,a1),
answer(a1,b1),
answer(a1,b2),
answer(a2,a1),
answer(a2,b1),
answer(a2,b2),
answer(a3,a1),
answer(a3,b1),


Fernando Senz-Prez 22/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

answer(a3,b2)
}
Info: 9 tuples computed.
DES-SQL> % Inner Join
DES-SQL> select a from a inner join b on a.a=b.b;
answer(a) ->
{
answer(a1)
}
Info: 1 tuple computed.
DES-SQL> % Left Join
DES-SQL> select * from a left join b on a.a=b.b;
answer(a.a, b.b) ->
{
answer(a1,a1),
answer(a2,null),
answer(a3,null)
}
Info: 3 tuples computed.
DES-SQL> % Right Join
DES-SQL> select * from a right join b on a.a=b.b;
answer(a.a, b.b) ->
{
answer(a1,a1),
answer(null,b1),
answer(null,b2)
}
Info: 3 tuples computed.
DES-SQL> % Full Join
DES-SQL> select * from a full join b on a.a=b.b;
answer(a.a, b.b) ->
{
answer(a1,a1),
answer(a1,null),
answer(a2,null),
answer(a3,null),
answer(null,a1),
answer(null,b1),
answer(null,b2)
}
Info: 7 tuples computed.
DES-SQL> % Union
DES-SQL> select * from a union select * from b;
answer(a.a) ->
{
answer(a1),
answer(a2),
answer(a3),
answer(b1),
answer(b2)
}
Info: 5 tuples computed.
DES-SQL> % Difference
DES-SQL> select * from a except select * from b;


Fernando Senz-Prez 23/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

answer(a.a) ->
{
answer(a2),
answer(a3)
}
Info: 2 tuples computed.
Info: Batch file processed.
DupIicales aie disalIed ly defauIl, i.e., ansveis aie sel-oiienled. ul lhey can
le enalIed as veII, vhich is usefuI in DalaIog, SQL and RA queiies (see Seclion 4.1.9).
Ioi inslance:

DES-Prolog> /duplicates on
Info: Duplicates are on.

DES-Prolog> /datalog projection(X)
{
projection(a1),
projection(a1),
projection(a2)
}
Info: 3 tuples computed.
3.3 +elational 2lge*ra Mode
In lhis node, queiies aie senl lo lhe ReIalionaI AIgelia (RA) piocessoi, vheieas
connands (cf. Seclion 5.14) aie senl lo lhe connand piocessoi. RA queiies can end
vilh an oplionaI senicoIon in singIe-Iine node. MuIli-Iine node iequiies lhe ending
senicoIon. RA node is enalIed via lhe connand /ra. DalaIog and SQL queiies
cannol le handIed ly lhis node.
If ve vanl lo deveIop an anaIogous RA exanpIe session lo lhe foinei
exanpIes, ve can sulnil lhe fiisl inpuls (aIso avaiIalIe in lhe fiIe
examples/relop.ra) Iisled leIov. Nov, ansvei ieIalions lo RA queiies aie
denoled ly lhe ieIalion nane answer. As lefoie, Iines slailing ly eilhei % oi -- aie
sinpIy ienaiks. If you vish lo aulonalicaIIy iepioduce lhe foIIoving inleiaclive
session of inpuls, you can lype /process examples/relop.ra (nolice lhal you
nusl onil examples/ if you aie in lhis diiecloiy aIieady):

DES-RA> % Testing the just inserted values
DES-RA> select true (a);
answer(a.a:string(varchar)) ->
{
answer(a1),
answer(a2),
answer(a3)
}
Info: 3 tuples computed.
DES-RA> select true (b);
answer(b.b:string(varchar)) ->
{
answer(a1),
answer(b1),
answer(b2)


Fernando Senz-Prez 24/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

}
Info: 3 tuples computed.
DES-RA> select true (c);
answer(c.a:string(varchar),c.b:string(varchar)) ->
{
answer(a1,a1),
answer(a1,b2),
answer(a2,b2)
}
Info: 3 tuples computed.
DES-RA> % Projection
DES-RA> project a (c);
answer(c.a:string(varchar)) ->
{
answer(a1),
answer(a2)
}
Info: 2 tuples computed.
DES-RA> % Selection
DES-RA> select a='a2' (a);
answer(a.a:string(varchar)) ->
{
answer(a2)
}
Info: 1 tuple computed.
DES-RA> % Cartesian product
DES-RA> a product b;
answer(a.a:string(varchar),b.b:string(varchar)) ->
{
answer(a1,a1),
answer(a1,b1),
answer(a1,b2),
answer(a2,a1),
answer(a2,b1),
answer(a2,b2),
answer(a3,a1),
answer(a3,b1),
answer(a3,b2)
}
Info: 9 tuples computed.
DES-RA> % Theta Join
DES-RA> select a.a=b.b (a product b);
answer(a.a:string(varchar),b.b:string(varchar)) ->
{
answer(a1,a1)
}
Info: 1 tuple computed.
DES-RA> a zjoin a.a=b.b b;
answer(a.a:string(varchar),b.b:string(varchar)) ->
{
answer(a1,a1)
}
Info: 1 tuple computed.
DES-RA> % Natural Inner Join


Fernando Senz-Prez 25/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES-RA> a njoin c;
answer(a.a:string(varchar),c.b:string(varchar)) ->
{
answer(a1,a1),
answer(a1,b2),
answer(a2,b2)
}
Info: 3 tuples computed.
DES-RA> % Left Outer Join
DES-RA> a ljoin a.a=b.b b;
answer(a.a:string(varchar),b.b:string(varchar)) ->
{
answer(a1,a1),
answer(a2,null),
answer(a3,null)
}
Info: 3 tuples computed.
DES-RA> % Right Outer Join
DES-RA> a rjoin a.a=b.b b;
answer(a.a:string(varchar),b.b:string(varchar)) ->
{
answer(a1,a1),
answer(null,b1),
answer(null,b2)
}
Info: 3 tuples computed.
DES-RA> % Full Outer Join
DES-RA> a fjoin a.a=b.b b;
answer(a.a:string(varchar),b.b:string(varchar)) ->
{
answer(a1,a1),
answer(a2,null),
answer(a3,null),
answer(null,b1),
answer(null,b2)
}
Info: 5 tuples computed.
DES-RA> % Union
DES-RA> a union b;
answer(a.a:string(varchar)) ->
{
answer(a1),
answer(a2),
answer(a3),
answer(b1),
answer(b2)
}
Info: 5 tuples computed.
DES-RA> % Difference
DES-RA> a difference b;
answer(a.a:string(varchar)) ->
{
answer(a2),
answer(a3)


Fernando Senz-Prez 26/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

}
Info: 2 tuples computed.
DES-RA> % Intersection
DES-RA> a intersect b;
answer(a.a:string(varchar)) ->
{
answer(a1)
}
Info: 1 tuple computed.
DES-RA> % Grouping
DES-RA> group_by a a,count(*) true (c);
answer(c.a:string(varchar),$a3:number(integer)) ->
{
answer(a1,2),
answer(a2,1)
}
Info: 2 tuples computed.
DES-RA> % Renaming
DES-RA> select a1.a<a2.a ((rename a1(a) (a)) product (rename
a2(a) (a)));
answer(a1.a:string(varchar),a2.a:string(varchar)) ->
{
answer(a1,a2),
answer(a1,a3),
answer(a2,a3)
}
Info: 3 tuples computed.
DES-RA> % Duplicate elimination
DES-RA> /duplicates off
Info: Duplicates are already disabled.
DES-RA> project a (c);
answer(c.a:string(varchar)) ->
{
answer(a1),
answer(a2)
}
Info: 2 tuples computed.
DES-RA> /duplicates on
DES-RA> project a (c);
answer(c.a:string(varchar)) ->
{
answer(a1),
answer(a1),
answer(a2)
}
Info: 3 tuples computed.
DES-RA> distinct (project a (c));
answer(c.a:string(varchar)) ->
{
answer(a1),
answer(a2)
}
Info: 2 tuples computed.


Fernando Senz-Prez 27/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

3.4 ?rolog Mode
This node is enalIed via lhe connand /prolog and goaIs aie senl lo lhe
IioIog piocessoi. Assuning lhal lhe fiIe relop.dl has leen aIieady consuIled, Iels
considei lhe foIIoving exanpIe:

DES-Prolog> projection(X)
projection(a1)
? (type ; for more solutions, <Intro> to continue) ;
projection(a1)
? (type ; for more solutions, <Intro> to continue) ;
projection(a2)
? (type ; for more solutions, <Intro> to continue) ;
no

DES-Prolog> /datalog projection(X)
{
projection(a1),
projection(a2)
}
Info: 2 tuples computed.
The execulion of lhis goaI aIIovs lo noling lhe lasic diffeiences lelveen IioIog
and DalaIog engines. Iiisl, lhe foinei seaiches foi soIulions, one-ly-one, lhal salisfy
lhe goaI projection(X). The Iallei gives lhe vhoIe neaning
2
of lhe usei-defined
ieIalion projection vilh lhe queiy projection(X) al a line. And, second, nole
lhe defauIl sel-oiienled lehavioui of lhe DalaIog engine, vhich discaids dupIicales in
lhe ansvei.
3.% Ca0eats
Since lhe DalaIog node pionpl accepls DalaIog, SQL and RA queiies, a given
queiy can le inleipieled in noie lhan one Ianguage. Lel's considei lhe foIIoving
syslen session, in vhich a lalIe is ciealed and an RA queiy is sulnilled:

DES> create table t(a int)
DES> distinct (t)
Info: Processing:
answer :-
distinct(t).
Warning: Undefined predicate(s): [t/0]
{
}
Info: 0 tuples computed.
Heie, ve gel an unexpecled oulpul coning fion lhe DalaIog inleipielei, as
such inpul couId le inleipieled lolh as a DalaIog queiy and an RA queiy. To
oveicone such silualions, sinpIy piecede lhe queiy ly lhe Ianguage seIeclion
connand, as foIIovs:


2
The neaning of a ieIalion is lhe sel of facls infeiied lolh exlensionaIIy and
inlensionaIIy fion lhe piogian.


Fernando Senz-Prez 28/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> /ra distinct (t)
answer(t.a:number(integer)) ->
{
}
Info: 0 tuples computed.
AIleinaliveIy, svilch lo lhe olhei queiy piocessoi:

DES> /ra
DES-RA> distinct (t)
Anolhei exanpIe is lhe division opeialoi:

DES> create table t(a int, b int)
DES> create table s(a int)
DES> t division s
Error: Incompatible schemas in division operation: t division s
DES> /ra t division s
answer(t.b:number(integer)) ->
{
}
Info: 0 tuples computed.
As lhe queiy t division s is fiislIy inleipieled as a DalaIog queiy, lolh t
and s aie assuned lo le piedicales of aiily O.
3." !etting @el&
You can gel usefuI infoinalion vilh lhe foIIoving connands:
/help. Shovs lhe Iisl of avaiIalIe connands, vhich aie expIained in Seclion 5.14.
/help Keyword. To iequesl heIp on a given keyvoid (connand oi luiIl-in).
/builtins. Shovs lhe Iisl of luiIl-ins, vhich aie expIained in Seclion 4.5.
AIso, visil lhe URL foi Iasl infoinalion:

http://des.sourceforge.net/
IinaIIy, you can conlacl lhe aulhoi via lhe e-naiI addiess:

fernan@sip.ucm.es
4. #uery $anguages
DLS has evoIved fion a quile sinpIe DalaIog inleipielei lo ils cuiienl slale,
vhich ieIies on a deduclive dalalase engine vhich can le queiied vilh eilhei DalaIog,
SQL oi RA Ianguages. In addilion, a IioIog inleiface is aIso piovided in oidei lo
highIighl lhe diffeiences lelveen DalaIog and IioIog syslens. Since DLS is inlended
lo sludenls, il has no fuII-lIovn fealuies of eilhei slale-of-lhe-ail IioIog, DalaIog oi
SQL-lased syslens. Hovevei, il has nany fealuies lhal nake il appeaIing as an
educalionaI looI, aIong vilh lhe noveI inpIenenlalions of decIaialive delugging
(seclions 5.9 and 5.1O) and lhe lesl case geneialoi (Seclion 5.11). In lhis seclion, ve
desciile ils foui queiy Ianguages: DalaIog, SQL, RA, and IioIog.


Fernando Senz-Prez 2/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The dalalase is shaied ly aII lhe queiy Ianguages, so lhal queiies oi goaIs can
iefei lo any oljecl defined using any Ianguage. Hovevei, lheie aie sone dependenl
issues lhal nusl le laken inlo accounl. Ioi inslance, once a DalaIog facl is Ioaded inlo
lhe dalalase, lhe ieIalion il defines can le queiied in DalaIog. ul, if one vanls lo
access lhis ieIalion fion eilhei SQL oi RA, lvo aIleinalives aie piovided: 1) Define lhe
sane ieIalion in SQL via a create table slalenenl (Seclion 4.2.4.1), and 2) DecIaie
lypes foi lhe lalIe (Seclion 4.1.15.1). This pailicuIai issue cones fion lhe facl lhal
DalaIog ieIalions have unnaned alliilules, and a posilionaI iefeience is used foi
accessing lhose ieIalions. In luin, SQL and RA use a nolalionaI synlax, giving nanes lo
ieIalion aigunenls. To iIIusliale lhe fiisl aIleinalive, Iels considei lhe foIIoving
session:

DES> /assert t(1)
DES> t(X)
{
t(1)
}
Info: 1 tuple computed.
DES> select * from t
Error: Unknown table or view "t"
DES> create table t(a int);
DES> select * from t;
answer(t.a:number(integer)) ->
{
answer(1)
}
Info: 1 tuple computed.
The eiioi alove iefIecls lhal t is nol a knovn oljecl in lhe dalalase schena.
IoIIoving lhe second aIleinalive lo access a DalaIog ieIalion fion SQL:

DES> /assert t(1)
DES> :-type(t,[a:int])
DES> select * from t
answer(t.a:number(integer)) ->
{
answer(1)
}
Info: 1 tuple computed.
4.1 Datalog
Since DalaIog slens fion IioIog, ve have adopled aInosl aII lhe IioIog synlax
convenlions foi viiling DalaIog piogians (lhe ieadei is assuned lo have lasic
knovIedge aloul IioIog). Synlax foIIovs IioIog ISO slandaid |ISOOOj (consideiing ils
synlax as a sulsel of IioIog). We aIIov (iecuisive) DalaIog piogians vilh slialified
negalion |UIIn95j, i.e., noinaI Iogic piogians vilhoul funclion synloIs. Slialificalion
is inposed lo ensuie a cIeai senanlics vhen negalion is invoIved, and funclion
synloIs aie nol aIIoved in oidei lo guaianlee leininalion of queiies, a naluiaI
iequiienenl vilh iespecl lo a (ieIalionaI) dalalase usei vho is nol alIe lo deaI vilh
conpound dala.


Fernando Senz-Prez 3!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Connands aie sonevhal diffeienl foi IioIog piogianneis as lhey aie
accusloned lo (see Seclion 5.14). AIso, exceplions aie noled vhen necessaiy.
4.1.1 Synta)
Definilions foi DalaIog nainIy cone fion lhe fieId of Logic Iiogianning.,
foIIoving |LIoyd87j, iefeiiing lhe ieadei lo lhis look foi a noie geneiaI piesenlalion
of Logic Iiogianning. Nexl, sone definilions foi undeislanding lhe synlax of
piogians, queiies and vievs aie inlioduced.
Nunleis. Inlegeis and fIoal nunleis aie aIIoved. A nunlei is a fIoal vhenevei
lhe nunlei conlains a dol (.) lelveen lvo digils. The iange depends on lhe IioIog
pIalfoin leing used. Negalive nunleis aie idenlified ly a pieceding ninus (-), as
usuaI.
Scienlific nolalion is suppoiled as: aEb, vheie a is a fiaclionaI nunlei (aIvays
incIuding a dol), and b is an inlegei, vhich nay slail vilh + oi (lul il is nol
iequiied).
LxanpIes of nunleis aie 1, 1.1, -1.0, 1.2E34, 1.2E+34, and 1.2E-34.
Nole lhal -1., +1, .1, 1.E23, and 1E23 aie nol vaIid nunleis. A pIus sign is nol
pail of a posilive nunlei, hovevei, lolh a pIus and a ninus sign can le used as a
piefix unaiy opeialoi in aiilhnelicaI expiessions (cf. Seclion 4.5.4.1) and aIso
foIIoving lhe synloI E in scienlific nolalion, as aIieady seen.
Conslanls. A conslanl can le:
o A nunlei (inlegei oi fIoal).
o Any sequence of aIphanuneiic chaiacleis (incIuding lhe undeiscoie _),
slailing vilh a Ioveicase Iellei
o Any sequence of chaiacleis deIiniled ly singIe quoles.
LxanpIes of aIphanuneiic conslanls aie foo, foo_foo, 'foo foo', '2*3', and
'X'.
VaiialIes. VaiialIes aie viillen vilh aIphanuneiic chaiacleis, and aIleinaliveIy
slail vilh eilhei an uppeicase oi vilh an undeiscoie (_). Anonynous vaiialIes aie
aIso aIIoved, vhich aie denoled vilh a singIe undeiscoie. Lach occuiience of an
anonynous vaiialIe is consideied diffeienl fion any olhei anonynous vaiialIe.
Ioi inslance, in lhe iuIe a :- b(_),c(_). lolh goaIs do nol shaie vaiialIes. Any
vaiialIe slailing vilh an undeiscoie (eilhei anonynous oi nol) is ienoved fion a
conpuled queiy (cf. Seclion 4.1.7).
LxanpIes of vaiialIes aie: X, _X, _var, and _.
Unknovns. Unknovns aie iepiesenled as nuII vaIues and aie viillen aIleinaliveIy
as lolh null and '$NULL'(ID), vheie ID is a unique idenlifiei. The fiisl foin is
used foi noinaI useis, vhiIsl lhe second one is inlended foi deveIopnenl uses (cf.
development connand in Seclion 5.14.7).
Teins. Teins can le:
o Nonconpound. VaiialIes oi conslanls.


Fernando Senz-Prez 31/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

o Conpound. As in IioIog, lhey have lhe foin t(t1, ..., tn), vheie t is
a funclion synloI (funcloi), and ti (1 < i < n) aie leins.
Up lo lhe cuiienl veision, conpound leins can onIy occui in aiilhnelic
expiessions. Theii funclion synloIs can le any of lhe luiIl-in aiilhnelic opeialois
and funclions (cf. Seclion 4.5.2). These opeialois can le:
o Infix, as addilion (e.g., 1+2)
o Iiefix, as lilvise negalion (e.g., \1)
LxanpIes of leins aie: r(p), and p(X,Y), and X > Y.
Alons. An alon has lhe foin a(t1, ..., tn), vheie a is a piedicale (ieIalion)
synloI, and ti (0 < i < n) aie leins. If i is 0, lhen lhe alon is sinpIy viillen as a.
Iosilive, giound alons aie used lo luiId lhe Heiliand univeise.
Theie aie seveiaI luiIl-in piedicales: is (foi evaIualing aiilhnelicaI expiessions),
aiilhnelic funclions, (infix and piefix) opeialois and conslanls, and conpaiison
opeialois. Conpaiison opeialois aie infix, as Iess-lhan. Ioi exanpIe, 1 < 2 is a
posilive alon luiIl fion an infix luiIl-in conpaiison opeialoi (see Seclion 4.5.1).
LxanpIes of alons aie: p, r(a,X), 1 < 2, and X is 1+2.
Nole lhal p(1+2) and p(t(a)) aie nol vaIid alons.
Condilions. A condilion is a ooIean expiession conlaining conjunclions (,/2),
disjunclions (;/2), luiIl-in conpaiison opeialois, conslanls and vaiialIes.
Ioui exanpIes of condilions aie: X>1, X=Y, (X>Y,Y>Z), (X=<Y;Z<0).
Nole lhal X>Y+Z is nov suppoiled, il can le soIved vhenevei lhe iuIe vheie il
occuis is safe (cf. Seclion 5.3).
ReIalion funclions. A funclion has lhe foin f(a1, , an), vheie f is a funclion
nane, ai aie ils aigunenls, and naps lo a ieIalion. OnIy luiIl-in funclions aie
aIIoved. The cuiienl piovision of luiIl-in funclions incIudes, anong olheis:
o not(a). Inlended foi conpuling lhe negalion of ils singIe aigunenl a.
o lj(a1,a2,a3). Inlended foi conpuling lhe left oulei join of lhe ieIalions
a1 (Iefl ieIalion) and a2 (iighl ieIalion), connilling lhe condilion (ooIean
expiession) a3 (join condilion).
o rj(a1,a2,a3). Inlended foi conpuling lhe right oulei join of lhe ieIalions
a1 (Iefl ieIalion) and a2 (iighl ieIalion), connilling lhe condilion (ooIean
expiession) a3 (join condilion).
o fj(a1,a2,a3). Inlended foi conpuling lhe full oulei join of lhe ieIalions
a1 (Iefl ieIalion) and a2 (iighl ieIalion), connilling lhe condilion (ooIean
expiession) a3 (join condilion).
Nole lhal oulei join funclions can le nesled.
LileiaIs. LileiaIs can le:
o Iosilive. An alon.


Fernando Senz-Prez 32/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

o Negalive. A negaled lody of lhe foin not(Body), vheie Body is a lody
(cf. nexl seclion). Negalive IileiaIs aie used lo expiess lhe negalion of a
ieIalion (eilhei as a queiy oi as a pail of a iuIe lody).
o Disjunclive. A disjunclive IileiaI is of lhe foin l;r , vheie l and r aie
IileiaIs.
o Divided. A divided IileiaI is of lhe foin l division r, vheie l and r aie
IileiaIs.
LxanpIes of IileiaIs aie:
p
r(a,X)
not(q(X,b))
not(a;b)
r(a,X);not(q(X,b)),
1 < 2
t(X,Y) division s(Y)
X is 1+2
Shoilhands foi conpound goaIs as not(a;b) aie aIIoved as veII, vhich slands
foi not((a;b)).
A IileiaI can occui in iuIe lodies, queiies, and viev lodies.
Synlax of luiIl-ins aie expIained in lheii coiiesponding foilhconing seclions.
4.1.2 +ules
DalaIog iuIes have lhe foin head :- body, oi sinpIy head. olh end vilh a
dol. A DalaIog head is a posilive alon lhal uses no luiIl-in piedicale synloI. A
DalaIog lody conlains a conna-sepaialed sequence of IileiaIs vhich nay conlain
luiIl-in synloIs as Iisled in Seclion 4.5, as veII as disjunclions (;/2) and divisions
(division/2).
4.1.3 ?rograms
DLS piogians consisl of a nuIlisel of iuIes. Iiogians nay conlain ienaiks. A
singIe-Iine ienaik slails vilh lhe synloI %, and ends al lhe end of Iine. ConsuIled
piogians can aIso conlain nuIli-Iine ienaiks, encIosed lelveen /* and */, vhich can
le nesled.
4.1.4 #ueries
A (posilive) queiy is lhe nane of a ieIalion vilh as nany aigunenls as lhe aiily
of lhe ieIalion (a posilive IileiaI). Lach one of lhese aigunenls can le a vaiialIe oi a
conslanl, a conpound lein is nol aIIoved lul as an aiilhnelic expiession. uiIl-in
ieIalions nay iequiie ieIalions and condilions as aigunenls. A negalive queiy is
viillen as not(Query).


Fernando Senz-Prez 33/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Queiies aie lyped al lhe DLS syslen pionpl. The ansvei lo a queiy is lhe
(nuIli)sel of alons nalching lhe queiy vhich aie deduced in lhe conlexl of lhe
piogian, fion lolh lhe exlensionaI and inlensionaI dalalase. A queiy vilh vaiialIes
foi aII lhe aigunenls of lhe queiied ieIalion gives lhe vhoIe sel of deduced facls
(neaning) defining lhe ieIalion, as lhe queiy a(X) in lhe exanpIe of Seclion 3. If a
queiy conlains a conslanl in an aigunenl posilion, il neans lhal lhe queiy piocessing
viII seIecl lhe facls fion lhe neaning of lhe ieIalion such lhal lhe aigunenl posilion
nalches vilh lhe conslanl (i.e., anaIogous lo a seIecl ieIalionaI opeialion). This is lhe
case of lhe queiy a(a3) in lhe sane exanpIe.
You can aIso viile conjunclive queiies on lhe fIy, such as a(X), b(X) (see
Seclion 4.1.6). uiIl-in conpaiison opeialois (Iisled in Seclion 4.5.1) can le safeIy used
in queiies vhenevei lheii aigunenls aie giound al evaIualion line (excepling
equaIily, vhich peifoins unificalion). Disjunclive queiies aie aIso aIIoved, loo, such as
a(X); b(X). ConcIuding, a queiy foIIovs lhe sane synlax as iuIe lodies.
If onIy a Iiniled nunlei of lupIes in lhe ansvei aie iequiied, one can sulnil
lhe queiy as top(N,Query), vheie N is lhe naxinun nunlei of lupIes lo le
ieluined.
AIso, queiy ansveis can le soiled vilh order_by(Query, [Expr1, ,
ExprN], [Ord1, , OrdN]) oi sinpIy order_by(Query, [Expr1, ,
ExprN]), vheie Expri is an expiession and Ordi can le eilhei a (foi ascending
oidei) oi d (foi descending oidei). The defauIl ansvei oideiing (sel vilh
/order_answer) is oveiiided.

DES> /assert t(3,1)
DES> /assert t(2,2)
DES> /assert t(1,3)
DES> /assert t(2,1)
DES> /order_answer off
DES> t(X,Y)
{
t(3,1),
t(2,2),
t(1,3),
t(2,1)
}
Info: 4 tuples computed.
DES> /order_answer off
DES> t(X,Y)
{
t(1,3),
t(2,1),
t(2,2),
t(3,1)
}
Info: 4 tuples computed.
DES> order_by(t(X,Y),[Y])
Info: Processing:
answer(X,Y) :-
order_by(t(X,Y),[Y],[a]).
{
answer(3,1),


Fernando Senz-Prez 34/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

answer(2,1),
answer(2,2),
answer(1,3)
}
Info: 4 tuples computed.
DES> order_by(t(X,Y),[X],[d])
Info: Processing:
answer(X,Y) :-
order_by(t(X,Y),[X],[d]).
{
answer(3,1),
answer(2,2),
answer(2,1),
answer(1,3)
}
Info: 4 tuples computed.
DES> order_by(t(X,Y),[X,Y],[d,a])
Info: Processing:
answer(X,Y) :-
order_by(t(X,Y),[X,Y],[d,a]).
{
answer(3,1),
answer(2,1),
answer(2,2),
answer(1,3)
}
Info: 4 tuples computed.
Nole, hovevei, lhal oideiing affecls lhe iesuIl of a conpulalion. The nexl
exanpIe shovs hov, depending on lhe oidei ciileiia, lhe ansvei is diffeienl:

DES> top(1,order_by(t(X,Y),[X],[a]))
Info: Processing:
answer(X,Y)
in the program context of the exploded query:
answer(X,Y) :-
top(1,'$p0'(Y,X)).
'$p0'(Y,X) :-
order_by(t(X,Y),[X],[a]).
{
answer(1,3)
}
Info: 1 tuple computed.
DES> top(1,order_by(t(X,Y),[X],[d]))
Info: Processing:
answer(X,Y)
in the program context of the exploded query:
answer(X,Y) :-
top(1,'$p0'(Y,X)).
'$p0'(Y,X) :-
order_by(t(X,Y),[X],[d]).
{
answer(3,1)
}
Info: 1 tuple computed.


Fernando Senz-Prez 35/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.1.% Aem&orary Vie3s
Tenpoiaiy vievs aIIov you lo viile conjunclive queiies on lhe fIy. A
lenpoiaiy viev is a iuIe vhich is added lo lhe dalalase, ils head is consideied as a
queiy and execuled. Afleivaids, lhe iuIe is deIeled. Tenpoiaiy vievs aie usefuI foi
quickIy sulnilling conjunclive queiies. Ioi inslance, lhe viev:

DES> d(X) :- a(X), not(b(X))
conpules lhe sel diffeience lelveen lhe sels a and b, piovided lhey have leen aIieady
defined.
Nole lhal lhe viev is evaIualed in lhe conlexl of lhe piogian, so, if you have
noie iuIes aIieady defined vilh lhe sane nane and aiily of lhe iuIe's head, lhe
evaIualion of lhe viev viII ieluin ils neaning undei lhe vhoIe sel of iuIes nalching
lhe queiy. Ioi inslance:

DES> a(X) :- b(X)
conpules lhe sel union of lhe sels a and b, piovided lhey have leen aIieady defined.
4.1." 2utomatic Aem&orary Vie3s
Aulonalic lenpoiaiy vievs, shoilIy aulovievs, aie lenpoiaiy vievs vhich do
nol need a head and aIIovs you lo viile conjunclive queiies on lhe fIy. When you
viile a conjunclive queiy, a nev lenpoiaiy ieIalion, naned answer, is luiIl vilh as
nany aigunenls as vaiialIes occui in lhe conjunclive queiy. answer is a ieseived
void and cannol le used foi defining any olhei ieIalion. As an exanpIe of an
auloviev, Iels considei:

DES> a(X),b(Y)

Info: Processing:
answer(X,Y) :-
a(X),
b(Y).
{
answer(a1,a1),
answer(a1,b1),
answer(a1,b2),
answer(a2,a1),
answer(a2,b1),
answer(a2,b2),
answer(a3,a1),
answer(a3,b1),
answer(a3,b2)
}
Info: 9 tuples computed.
vhich conpules lhe Cailesian pioducl of lhe ieIalions a and b, piovided lhey have
leen aIieady defined as:

a(a1).
a(a2).
a(a3).


Fernando Senz-Prez 36/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

b(b1).
b(b2).
b(a1).
4.1.( Underscored Varia*les
An undeiscoied vaiialIe (a vaiialIe slailing vilh lhe undeiscoie synloI '_') is
handIed siniIai lo IioIog. Il is assuned lo le of no inleiesl foi lhe ansvei, so lhal lhey
aie discaided fion lhe ansvei shouId lhey occui in lhe lody of a queiy, viev oi
auloviev (even in ils head). Ioi inslance, conpuling lhe piojeclion of a ieIalion t vilh
iespecl lo ils fiisl aigunenl can le sinpIy done as foIIovs:

DES> /assert t(1,2)
DES> /assert t(2,3)
DES> t(X,_)
Info: Processing:
answer(X) :-
t(X,_).
{
answer(1),
answer(2)
}
Info: 2 tuples computed.
inslead of having lo iesoil lo an auloviev such as:

DES> p(X):-t(X,Y)
Info: Processing:
p(X) :-
t(X,Y).
{
p(1),
p(2)
}
Info: 2 tuples computed.
AIso, Iel's considei olhei silualion, as foIIovs:

DES> /duplicates off
DES> t(X,Y)
{
t(1,1),
t(1,2),
t(3,3)
}
Info: 3 tuples computed.
DES> t(X,X)
{
t(1,1),
t(3,3)
}
Info: 2 tuples computed.
If you use inslead undeiscoied vaiialIes, you gel one ansvei lupIe:



Fernando Senz-Prez 37/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> t(_X,_X)
Info: Processing:
answer :-
t(_X,_X).
{
answer
}
Info: 1 tuple computed.
Hovevei, if dupIicales aie enalIed, you gel lvo ansvei lupIes, aIlhough lhe
conciele vaIues foi lhe aigunenls of t aie nol visilIe:

DES> /duplicates on
DES> t(_X,_X)
Info: Processing:
answer :-
t(_X,_X).
{
answer,
answer
}
Info: 2 tuples computed.
4.1.8 1egation
DLS ensuies lhal negalive infoinalion can le galheied fion a piogian vilh
negaled goaIs piovided lhal a iesliicled foin of negalion is used: Slialified negalion
|UIIn95j. This lioadIy neans lhal negalion is nol invoIved in a iecuisive conpulalion
palh, aIlhough il can use iecuisive iuIes. The foIIoving piogian
3
iIIusliales lhis poinl:

a :- not(b).
b :- c,d.
c :- b.
c.
The queiy a succeeds vilh lhe neaning {a}. Olseive aIso lhal not(a) does
nol succeed, i.e., ils neaning is lhe enply sel.
DLS piovides lvo diffeienl aIgoiilhns foi conpuling negalion: strata (a
defauIl aIgoiilhn foIIoving a lollon-up lop-dovn-guided slialun saluialion) and
et_not (laken fion |SD91j), vhich aie seIecled via lhe connand /negation
Algorithm. (cf. Seclion 5.14.1O).
If you aie inleiesled in hov piogians vilh negalion aie soIved foi lhe
aIgoiilhn strata, you can find usefuI lhe foIIoving connands (cf. Seclion 5.14.7):

DES> /pdg

Nodes: [d/0,a/0,b/0,c/0]
Arcs : [a/0-b/0,c/0+b/0,b/0+d/0,b/0+c/0]


3
In fiIe negation.dl, Iocaled al lhe examples disliilulion diiecloiy. Adapled fion
|RSSWI97j.


Fernando Senz-Prez 38/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> /strata

[(d/0,1),(a/0,2),(b/0,1),(c/0,1)]
The fiisl connand shovs lhe piedicale dependency giaph (see, e.g., |ZCI+97j)
foi lhe Ioaded piogian. Iiisl, nodes in lhe giaph aie shovn in a Iisl vhose eIenenls I
aie piedicales vilh lheii aiilies vilh lhe foin piedicale/aiily. Nexl, aics in lhe giaph
aie shovn in a Iisl vhose eIenenles aie eilhei I+Q oi I-Q, vheie I and Q aie nodes in
lhe giaph. An aic I+Q neans lhal lheie exisls a iuIe such lhal I is lhe piedicale foi ils
head, and Q is lhe piedicale foi one of ils IileiaIs. If lhe IileiaI is negaled, lhe aic is
negalive, vhich is expiessed as I-Q. The giaph foi lhis piogian can le depicled as in
Iiguie 3.

b
c
a d
-
+
+
+

Iiguie 3. Iiedicale Dependency Ciaph foi negation.dl
The second connand shovs lhe slialun assigned lo each piedicale. This
assignnenl is conpuled ly foIIoving an aIgoiilhn lased on |UIIn95j, lul nodified
foi laking advanlage of lhe piedicale dependency giaph. Sliala aie shovn as a Iisl of
paiis (I,S), vheie I is a piedicale and S is ils assigned slialun. In lhis exanpIe, aII of
lhe piogian piedicales aie in slialun 1 lul a, vhich is assigned lo slialun 2. This
neans lhal if lhe neaning of a is lo le conpuled, lhen lhe neanings of piedicales in
Iovei sliala (and onIy lhose piedicales a depends on) have lo le fiislIy conpuled.
Since lhe aIgoiilhn strata does nol foIIov a nave lollon-up soIving, onIy
lhe neanings of iequiied piedicales aie conpuled. To iIIusliale lhis, considei lhe
queiy b foi lhe sane piogian. DLS conpules lhe piedicale dependency sulgiaph foi
b, i.e., aII of lhe piedicales vhich aie ieachalIe fion b, and, lhen, a slialificalion is
conpuled. Nolice lhe diffeienl infoinalion given ly lhe syslen foi soIving lhe queiies
a and b (heie, veilose oulpul is cuiienlIy enalIed vilh lhe connand /verbose on):

DES> a
Info: Computing by stratum: [b].
{
a
}
Info: 1 tuple computed.
DES> b
{
}
Info: 0 tuples computed.
Ioi lhe goaI a, lhe syslen infoins lhal b is pieviousIy conpuled (neveilheIess
laking advanlage of lhe exlension lalIe nechanisn), vheieas foi lhe goaI b lheie is no
need of iesoiling lo lhe slialun-ly-slialun soIving.
IinaIIy, consuIl aIso Seclion 5.3 foi Iinilalions in lhe use of negalion.


Fernando Senz-Prez 3/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.1. Du&licates
DupIicales in ansveis aie ienoved ly defauIl. Hovevei, il is aIso possilIe lo
enalIe lhen vilh lhe connand /duplicates on. This aIIovs lo geneiale ansveis as
nuIlisels inslead of as lhe lypicaI sel-oiienled deduclive syslens lehave. Conpuling
lhe neaning of a ieIalion conlaining dupIicales in lhe exlensionaI dalalase (i.e., ils
facls) viII incIude aII of lhen in lhe ansvei, as in:

DES> /duplicates on
DES> /assert t(1)
DES> /assert t(1)
DES> t(X)
{
t(1),
t(1)
}
Info: 2 tuples computed.
RuIes can aIso le souice of dupIicales, as in:

DES> /assert s(X):-t(X)
DES> s(X)
{
s(1),
s(1)
}
Info: 2 tuples computed.
In addilion, iecuisive iuIes aie dupIicale souices, as in:

DES> /assert t(X):-t(X)
DES> t(X)
{
t(1),
t(1),
t(1),
t(1)
}
Info: 4 tuples computed.
vheie lvo lupIes diieclIy cone fion lhe lvo facls foi t/1, and lhe olhei lvo fion lhe
singIe iecuisive iuIe. Again, adding lhe sane iecuisive iuIe yieIds:

DES> /assert t(X):-t(X)
DES> t(X)
{
t(1),
t(1),
t(1),
t(1),
t(1),
t(1),
t(1),
t(1),
t(1),


Fernando Senz-Prez 4!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

t(1)
}
Info: 10 tuples computed.
vheie lhis ansvei conlains lhe oulcone due lo: lvo lupIes diieclIy fion lhe lvo facls,
and foui lupIes foi each iecuisive iuIe. The fiisl iecuisive iuIe is souice of foui lupIes
lecause of lhe lvo facls and lhe lvo lupIes fion lhe second iecuisive iuIe.
AnaIogousIy, lhe second iecuisive iuIe is souice of anolhei foui lupIes: lvo facls and
lhe lvo lupIes fion lhe fiisl iecuisive iuIe.
The iuIe of lhunl lo undeisland dupIicales in iecuisive iuIes is lo considei aII
possilIe conpulalion palhs in lhe dependency giaph, slopping vhen a (iecuisive)
node aIieady used in lhe conpulalion is ieached.
Il is aIso possilIe lo discaid dupIicales foi an alon vilh lhe nelapiedicale
distinct/1. Ioi inslance, Iels considei lhe foIIoving vilh lhe sane exanpIe alove:

DES> distinct(t(X))
Info: Processing:
answer(X) :-
distinct(t(X)).
{
answer(1)
}
Info: 1 tuple computed.
Such queiy is equivaIenl lo lhe foIIoving SQL slalenenl, piovided lhal
neladala is avaiIalIe foi lhe ieIalion t:

DES> :-type(t(a:int))
DES> select distinct * from t
answer(t.a) ->
{
answer(1)
}
Info: 1 tuple computed.
As il vouId le expecled, dupIicales aie onIy discaided foi lhe caII
distinct(Atom), lul nol foi olhei occuiiences of Atom duiing queiy soIving. Thus:

DES> t(X),distinct(t(X))
Info: Processing:
answer(X) :-
t(X),
distinct(t(X)).
{
answer(1),
answer(1),
answer(1),
answer(1),
answer(1),
answer(1),
answer(1),
answer(1),
answer(1),
answer(1)


Fernando Senz-Prez 41/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

}
Info: 10 tuples computed.
Conpaie lhis lo lhe caII:

DES> t(X),t(X)
Info: Processing:
answer(X) :-
t(X),
t(X).
{
answer(1),
...
answer(1)
}
Info: 100 tuples computed.
A sulsel of aigunenls in an alon can le seIecled foi discaiding dupIicales. To
lhis end, lhe nelapiedicale distinct/2 is piovided. Ils fiisl aigunenl is lhe Iisl of
vaiialIes foi vhich dupIicales aie nol iequiied, i.e., each conciele assignnenl of vaIues
lo aII vaiialIes in lhe Iisl nusl le diffeienl. So, Iel's considei lhe foIIoving session:

DES> /listing
t(1,1).
t(1,2).
t(2,1).
Info: 3 rules listed.
DES> distinct([X],t(X,Y))
Info: Processing:
answer(X) :-
distinct([X],t(X,Y)).
{
answer(1),
answer(2)
}
Info: 2 tuples computed.
In addilion, discaiding dupIicales can le peifoined in lhe conlexl of
aggiegales:

DES> count(distinct(t(X)),C)
Info: Processing:
answer(C)
in the program context of the exploded query:
answer(C) :-
count('$p0'(X),[],C).
'$p0'(A) :-
distinct(t(A)).
{
answer(1)
}
Info: 1 tuple computed.
See aIso Seclion 4.1.12 foi discaiding dupIicales in aggiegales.


Fernando Senz-Prez 42/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.1.1' 1ull Values
The nuII vaIue is incIuded in each piogian signaluie foi denoling unknovns,
in a siniIai vay il is an inheienl pail of cuiienl ieIalionaI dalalase syslens.
Conpaiing nuII vaIues in DalaIog opens a nev scenaiio: Tvo nuII vaIues aie nol
(knovn lo le) equaI, and aie (nol knovn lo le) dislincl. The foIIoving iIIusliales lhis
expecled lehavioui:

DES> null=null
{
}
Info: 0 tuples computed.

DES> null\=null
{
}
Info: 0 tuples computed.
Hovevei, foi lhe sane nuII vaIue, lhe equaIily shouId succeed, as in lhe
conjunclive queiy: X=null,X=X.
A nuII vaIue is inleinaIIy iepiesenled as '$NULL'(ID), vheie ID is a unique
idenlifiei (an inlegei). DeveIopnenl Iislings (enalIed via lhe connand
/development on) aIIov lo inspecl lhese idenlifieis, such as in:

DES> /development on
DES> p(X,Y):-X=null,Y=null,X=Y
Info: Processing:
p(X,Y) :-
X = '$NULL'(14),
Y = '$NULL'(15),
X = Y.
{
}
Info: 0 tuples computed.
DES> p(X,Y):-X=null,Y=null,X\=Y
Info: Processing:
p(X,Y) :-
X = '$NULL'(16),
Y = '$NULL'(17),
X \= Y.
{
}
Info: 0 tuples computed.
The luiIl-in piedicale is_null/1 lesls vhelhei ils singIe aigunenl is a nuII
vaIue:

DES> is_null(null)
{
is_null(null)
}
Info: 1 tuple computed.

DES> X=null,is_null(X)


Fernando Senz-Prez 43/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


Info: Processing:
answer(X) :-
X = null,
is_null(X).
{
answer(null)
}
Info: 1 tuple computed.
Ils counleipail piedicale is aIso piovided: is_not_null/1, vhich is liue if ils
aigunenl is nol a nuII vaIue.
Nole lhal fion a syslen inpIenenloi vievpoinl, nuIIs can nevei unify lecause
lhey aie iepiesenled ly diffeienl giound leins. On lhe olhei hand, disequaIily is
expIicilIy handIed in oidei lo faiI vhen conpaiing nuIIs.
LvaIualion of a given expiession incIuding al Ieasl one nuII vaIue aIvays
ieluins lhe sane conciele nuII vaIue. Thus, lvo expiessions incIuding nuII vaIues aie
consideied equivaIenl if lhey aie syntactically equaI (v.i.l. giound inslanlialions foi
nuII vaIues in pailicuIai). Ioi inslance, X=null,X+1=X+1 succeeds, vheieas
X=null,Y=null,X+1=Y+1 and X=null,X+1=1+X do nol.
4.1.11 =uter Boins
Thiee oulei join opeialions aie piovided (cf. Seclion 4.5.6), foIIoving ieIalionaI
dalalase queiy Ianguages (SQL, exlended ieIalionaI aIgelia): Iefl, iighl and fuII oulei
join. Having Ioaded lhe exanpIe piogian relop.dl, ve can sulnil lhe foIIoving
queiies:

DES> /c relop
DES> /listing a
a(a1).
a(a2).
a(a3).
DES> /listing b
b(a1).
b(b1).
b(b2).
DES> lj(a(X),b(Y),X=Y)
Info: Processing:
answer(X,Y) :-
lj(a(X),b(Y),X = Y).
{
answer(a1,a1),
answer(a2,null),
answer(a3,null)
}
Info: 3 tuples computed.
DES> rj(a(X),b(Y),X=Y)
Info: Processing:
answer(X,Y) :-
rj(a(X),b(Y),X = Y).
{
answer(a1,a1),


Fernando Senz-Prez 44/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

answer(null,b1),
answer(null,b2)
}
Info: 3 tuples computed.
DES> fj(a(X),b(Y),X=Y)
Info: Processing:
answer(X,Y) :-
fj(a(X),b(Y),X = Y).
{
answer(a1,a1),
answer(a1,null),
answer(a2,null),
answer(a3,null),
answer(null,a1),
answer(null,b1),
answer(null,b2)
}
Info: 7 tuples computed.
Nole lhal lhe lhiid paianelei is lhe join condilion. e avaie and do nol niss a
vheie condilion vilh a join condilion. Lels considei lhe alove queiy
lj(a(X),b(Y),X=Y). Do nol expecl lhe sane iesuIl as alove foi lhe foIIoving queiy:

DES> lj(a(X),b(X),true)
Info: Processing:
answer(X) :-
lj(a(X),b(X),true).
{
answer(a1)
}
Info: 1 tuple computed.
Heie, lhe sane vaiialIe X foi lhe ieIalions a and b neans lhal lupIes fion a
and b vilh lhe sane vaIue aie lo le joined, as in lhe nexl equivaIenl queiy:

DES> lj(a(X),b(Y),true),X=Y
Info: Processing:
answer(X,Y) :-
lj(a(X),b(Y),true),
X = Y.
{
answer(a1,a1)
}
Info: 1 tuple computed.
Oulei join ieIalions can le nesled as veII:

DES> lj(a(X),rj(b(Y),c(U,V),Y=U),X=Y)
Info: Processing:
answer(X,Y,U,V) :-
lj(a(X),rj(b(Y),c(U,V),Y = U),X = Y).
{
answer(a1,a1,a1,a1),
answer(a1,a1,a1,b2),
answer(a2,null,null,null),


Fernando Senz-Prez 45/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

answer(a3,null,null,null)
}
Info: 4 tuples computed.
Nole lhal conpound condilions nusl le encIosed lelveen paienlheses, as in:

DES> lj(a(X),c(U,V),(X>U;X>V))
Info: Processing:
answer(X,U,V)
in the program context of the exploded query:
answer(X,U,V) :-
lj(a(X),c(U,V),(X > U;X > V)).
{
answer(a1,null,null),
answer(a2,a1,a1),
answer(a2,a1,b2),
answer(a3,a1,a1),
answer(a3,a1,b2),
answer(a3,a2,b2)
}
Info: 6 tuples computed.
4.1.12 2ggregates
Aggiegales iefei lo funclions and piedicales lhal conpule vaIues vilh iespecl
lo a coIIeclion of vaIues inslead of a singIe vaIue. Aggiegales aie piovided ly neans of
five usuaI conpulalions: sum (cunuIalive sun), count (eIenenl counl), avg (aveiage),
min (nininun eIenenl), and max (naxinun eIenenl). In addilion, lhe Iess usuaI
times (cunuIalive pioducl) is aIso piovided. They lehave cIose lo nosl SQL
inpIenenlalions, i.e., ignoiing nuIIs.
DupIicale-fiee counleipails aie aIso piovided: sum_distinct,
count_distinct, avg_distinct, and times_distinct. Nole lhal foi nininun
and naxinun, no counleipails aie piovided since lhey vouId conpule lhe sane
iesuIls. These funclions lehave as lhe alove vhen dupIicales aie disalIed, vhich is lhe
defauIl node.
Any aiilhnelic expiession can le aigunenl of an aggiegale funclion.
4.1.12.1 2ggregate .unctions
An aggiegale funclion can occui in expiessions and ieluins a vaIue, as in
R=1+sum(X), vheie sum is expecled lo conpule lhe cunuIalive sun of possilIe
vaIues foi X, and X has lo le lound in lhe conlexl of a group_by piedicale (cf. nexl
seclion), vheiein lhe expiession aIso occui.
4.1.12.2 !rou&7*y ?redicate
A group_by piedicale encIoses a queiy foi vhich a given Iisl of vaiialIes
luiIds ansvei sels (gioups) foi aII possilIe vaIues of lhese vaiialIes. Lels considei lhe
foIIoving exceipl fion lhe fiIe aggregates.dl:

% employee(Name,Department,Salary)
employee(anderson,accounting,1200).
employee(andrews,accounting,1200).
employee(arlingon,accounting,1000).


Fernando Senz-Prez 46/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

employee(nolan,null,null).
employee(norton,null,null).
employee(randall,resources,800).
employee(sanders,sales,null).
employee(silver,sales,1000).
employee(smith,sales,1000).
employee(steel,sales,1020).
employee(sullivan,sales,null).
We can counl lhe nunlei of enpIoyees foi each depailnenl vilh lhe foIIoving
queiy:

DES> group_by(employee(N,D,S),[D],R=count)
Info: Processing:
answer(D,R) :-
group_by(employee(N,D,S),[D],R = count).
{
answer(accounting,3),
answer(null,2),
answer(resources,1),
answer(sales,5)
}
Info: 4 tuples computed.
Nole lhal lvo enpIoyees aie nol assigned lo any depailnenl yel (nolan and
norton). This queiy lehaves as an SQL usei vouId expecl, lhough nuIIs do nol have
lo iepiesenl lhe sane dala vaIue (in spile of lhis, such lupIes aie coIIecled in lhe sane
lag).
If ve ialhei vanl lo counl active enpIoyees (lhose vilh assigned saIaiies), ve
pose lhe foIIoving queiy:

DES> group_by(employee(N,D,S),[D],R=count(S))
Info: Processing:
answer(D,R) :-
group_by(employee(N,D,S),[D],R = count(S)).
{
answer(accounting,3),
answer(null,0),
answer(resources,1),
answer(sales,3)
}
Info: 4 tuples computed.
Nole lhal nuII depailnenls have no enpIoyee vilh assigned saIaiy.
Counling lhe nunlei of depailnenls fion lhe ieIalion employee needs lo
discaid dupIicales, as in:

DES> count_distinct(employee(N,D,S),D,T).
Info: Processing:
answer(T) :-
count_distinct(employee(N,D,S),D,[],T).
{
answer(3)
}


Fernando Senz-Prez 47/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Info: 1 tuple computed.
Condilions incIuding aggiegales on gioups can le slaled as veII (cf. having
condilions in SQL). Ioi inslance, lhe foIIoving queiy counls lhe aclive enpIoyees of
depailnenls vilh noie lhan one enpIoyee.

DES> group_by(employee(N,D,S),[D],count(S)>1)
Info: Processing:
answer(D) :-
group_by(employee(N,D,S),[D],(A = count(S),A > 1)).
{
answer(accounting),
answer(sales)
}
Info: 2 tuples computed.
Nole lhal lhe nunlei of enpIoyees can aIso le ieluined, as foIIovs:

DES> group_by(employee(N,D,S),[D],(R=count(S),R>1))
Info: Processing:
answer(D,R) :-
group_by(employee(N,D,S),[D],(R = count(S),R > 1)).
{
answer(accounting,3),
answer(sales,3)
}
Info: 2 tuples computed.
Condilions incIuding no aggiegales on lupIes of lhe inpul ieIalion (cf. SQL
FROM cIause) can aIso le used (cf. WHERE condilions in SQL). Ioi inslance, lhe
foIIoving queiy conpules lhe nunlei of enpIoyees vhose saIaiy is giealei lhan 1,OOO.

DES> group_by((employee(N,D,S),S>1000),[D],R=count(S))
Info: Processing:
answer(D,R)
in the program context of the exploded query:
answer(D,R) :-
group_by('$p2'(S,D,N),[D],R = count(S)).
'$p2'(S,D,N) :-
employee(N,D,S),
S > 1000.
{
answer(accounting,2),
answer(sales,1)
}
Info: 2 tuples computed.
Nole lhal lhe foIIoving queiy is nol equivaIenl lo lhe foinei, since vaiialIes in
lhe inpul ieIalion aie nol lound aflei a giouping conpulalion. The foIIoving queiy
iIIusliales lhis silualion, vhich geneiales a synlax eiioi.

DES> group_by(employee(N,D,S),[D],R=count(S)), S>1000
Error: Incorrect use of shared set variables in metapredicate:
[N,S]


Fernando Senz-Prez 48/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The piedicale group_by adnils a noie conpacl iepiesenlalion lhan ils SQL
counleipail. Lel's considei lhe foIIoving DalaIog session:

DES> /assert p(1,1)
DES> /assert p(2,2)
DES> /assert q(X,C):-group_by(p(X,Y),[X],(C=count;C=sum(Y)))
DES> q(X,C)
Info: Computing by stratum of [p(A,B)].
{
q(1,1),
q(2,1),
q(2,2)
}
Info: 3 tuples computed.
An anaIogous SQL session foIIovs:

DES-SQL> create table p(X int, Y int)
DES-SQL> create view q(X,C) as (select X,count(Y) as C from p
group by X) union (select X, sum(Y) as C from p group by X)
DES-SQL> select * from q
answer(q.X, q.C) ->
{
answer(1,1),
answer(2,1),
answer(2,2)
}
Info: 3 tuples computed.
4.1.12.3 2ggregate ?redicates
An aggiegale piedicale ieluins ils iesuIl in ils Iasl aigunenl posilion, as in
sum(p(X),X,R), vhich linds R lo lhe cunuIalive sun of vaIues foi X, piovided ly
lhe inpul ieIalion p. These aggiegale piedicales sinpIy aIIov anolhei vay of
expiessing aggiegales, in addilion lo lhe vay expIained jusl alove. Again, vilh lhe
sane fiIe, lhe foIIoving queiies aie aIIoved:

DES> count(employee(N,D,S),S,T)
Info: Processing:
answer(T) :-
count(employee(N,D,S),S,[],T).
{
answer(7)
}
Info: 1 tuple computed.
A group by opeialion is sinpIy specified ly incIuding lhe giouping vaiialIe(s)
in lhe head of a cIause, as in lhe foIIoving viev, vhich conpules lhe nunlei of aclive
enpIoyees ly depailnenl:

DES> c(D,C):-count(employee(N,D,S),S,C)
Info: Processing:
c(D,C) :-
count(employee(N,D,S),S,[D],C).
{


Fernando Senz-Prez 4/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

c(accounting,3),
c(null,0),
c(resources,1),
c(sales,3)
}
Info: 4 tuples computed.
Nole lhal lhe syslen adds lo lhe aggiegale piedicale an aigunenl vilh lhe Iisl
of giouping vaiialIes, vhich aie lhe ones occuiiing in lhe fiisl aigunenl of lhe
aggiegale piedicale lhal aIso occui in lhe head. This code liansIalion is iequiied foi lhe
aggiegale piedicale lo le conpule, aIlhough such foin has nol leen nade avaiIalIe lo
lhe usei.
Having condilions aie aIso aIIoved, incIuding lhen as anolhei goaI of lhe fiisl
aigunenl of lhe aggiegale piedicale as, foi inslance, in lhe foIIoving viev, vhich
conpules lhe nunlei of enpIoyees lhal eain noie lhan lhe aveiage:

DES> count((employee(N,D,S),avg(employee(N1,D1,S1),S1,A),S>A),C)
Info: Processing:
answer(C)
in the program context of the exploded query:
answer(C) :-
count('$p2'(A,S,D,N),[],C).
'$p2'(A,S,D,N) :-
employee(N,D,S),
avg(employee(N1,D1,S1),S1,[],A),
S > A.
{
answer(2)
}
Info: 1 tuple computed.
Nole lhal lhis queiy uses diffeienl vaiialIes in lhe sane aigunenl posilions foi
lhe lvo occuiiences of lhe ieIalion employee. Conpaie lhis lo lhe foIIoving queiy,
vhich conpules lhe nunlei of enpIoyees so lhal each one of lhen eains noie lhan
lhe aveiage saIaiy of his coiiesponding depailnenl. Heie, lhe sane vaiialIe nane D
has leen used lo iefei lo lhe depailnenl foi vhich lhe counling and aveiage aie
conpuled:

DES> count((employee(N,D,S),avg(employee(N1,D,S1),S1,A),S>A),C)
Info: Processing:
answer(C)
in the program context of the exploded query:
answer(C) :-
count('$p2'(A,S,N),[],C).
'$p2'(A,S,N) :-
employee(N,D,S),
avg(employee(N1,D,S1),S1,[],A),
S > A.
{
answer(3)
}
Info: 1 tuple computed.


Fernando Senz-Prez 5!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

AIso, as a iesliiclion of lhe cuiienl inpIenenlalion, keep in nind lhal having
condilions incIuding aggiegales (as lhe one incIuding lhe aveiage conpulalions alove)
can onIy occui in lhe fiisl aigunenl of an aggiegale. The foIIoving queiy, vhich
shouId le equivaIenl lo lhe Iasl one, vouId geneiale a iun-line exceplion:

DES> v(D):-
avg(employee(N1,D,S1),S1,A),count((employee(N,D,S),S>A),C)
Error: S > A will raise a computing exception at run-time.
Warning: This view is unsafe because of variable(s):
[A]
IinaIIy, iecaII lhal expiessions incIuding aggiegale funclions aie nol aIIoved in
conjunclion vilh aggiegale piedicales, lul onIy in lhe conlexl of a group_by
piedicale.
4.1.12.4 2ggregates and Du&licates
When dupIicales aie disalIed (defauIl oplion), aggiegale funclions opeiale ovei
sels, so lhal if lhe souice ieIalion foi an aggiegale conlains dupIicales, lhey aie
discaided. The foIIoving syslen session iIIusliales lhis:

DES> /duplicates off
DES> /assert t(1,2)
DES> /assert t(1,2)
DES> count(t(X,Y),C)
Info: Processing:
answer(C) :-
count(t(X,Y),[],C).
{
answer(1)
}
Info: 1 tuple computed.
On lhe olhei hand, enalIing dupIicales, lolh lupIes in lhe ieIalion t aie
counled unIess count_distinct is used:

DES> /duplicates on

DES> count(t(X,Y),C)
Info: Processing:
answer(C) :-
count(t(X,Y),[],C).
{
answer(2)
}
Info: 1 tuple computed.

DES> count_distinct(t(X,Y),C)
Info: Processing:
answer(C) :-
count_distinct(t(X,Y),[],C).
{
answer(1)
}
Info: 1 tuple computed.


Fernando Senz-Prez 51/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.1.13 DisCuncti0e 4odies
As inlioduced in Seclion 4.1.1, iuIe lodies can conlain disjunclions, such as lhe
one conlained in lhe piogian family.dl:

parent(X,Y) :-
father(X,Y)
;
mother(X,Y).
This cIause is equivaIenl lo:

parent(X,Y) :-
father(X,Y).
parent(X,Y) :-
mother(X,Y).
If you Iisl lhe dalalase conlenls via lhe connand /listing you viII gel lhe
fiisl foin vhen deveIopnenl Iislings aie off (via lhe connand /development off).
Olheivise, you gel lhe second one (connand /development on).
DalaIog vievs and aulovievs conlaining disjunclive lodies aie aIIoved, and
lhe syslen infoins aloul lhe piogian liansfoinalion needed lo conpule lhen. Ioi
inslance, you can diieclIy sulnil lhe iuIe alove as a viev al lhe DLS pionpl:

DES> parent(X,Y) :- father(X,Y) ; mother(X,Y)
Info: Processing:
parent(X,Y)
in the program context of the exploded query:
parent(X,Y) :-
father(X,Y).
parent(X,Y) :-
mother(X,Y).
{
parent(amy,fred),
parent(carolI,carolII),
parent(carolII,carolIII),
parent(fred,carolIII),
parent(grace,amy),
parent(jack,fred),
parent(tom,amy),
parent(tony,carolII)
}
Info: 8 tuples computed.
4.1.14 +elational Di0ision in Datalog
The piovided ieIalionaI division opeialion foi DalaIog foIIovs lhe oiiginaI
pioposaI of Codd |Codd72j lul, inslead of conpaiing schenas lased on coIunn
nanes, ve conpaie schenas lased on vaiialIe nanes. Civen a Iefl opeiand L and a
iighl opeiand R in a division opeialoi, lhe iesuIl is a ieIalion vilh as nany aigunenls
as vaiialIes aie in vais(L)-vais(R), vheie vais(R)vais(L) and vais(T) ieluins lhe
vaiialIes in a lein T.
Ioi exanpIe, given lhe dalalase:


Fernando Senz-Prez 52/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


t(1,1).
t(1,2).
t(2,1).
s(1).
s(2).
Then, lhe queiy:

t(X,Y) division s(Y)
ieluins:

{answer(1)}
Nov, Iel's considei lhal lhe ieIalions lo le divided conlain olhei aigunenls lhal
aie nol ieIevanl foi lhe division opeialoi. Ioi inslance, Iel's considei lhe ieIalion
work(employee, project, hours), undei an inluilive neaning. If ve vanl lo
knov lhe nane of each enpIoyee vho is voiking on each piojecl on vhich enpIoyee
smith is voiking, ve have lo piojecl lhe division opeiands foi lhe appiopiiale
aigunenls. Ioi inslance:

DES> /assert np_work(N,P) :- work(N,P,_)
DES> np_work(N,P) division np_work(smith,P)
Hovevei, ly using anonynous vaiialIes, il is possilIe lo onil lhe non-ieIevanl
vaiialIes (ly using an anonynous annolalion '_' foi lhen) foi lhe division opeialoi,
vilhoul needing lo piojecl lhe ieIevanl ones. IoIIoving lhe sane exanpIe, lhe sane
queiy can le sulnilled as sinpIy as:

DES> work(N,P,_) division work(smith,P,_)
Division can le nesled as veII. Ioi inslance, Iel's considei lhe ieIalion
team(team_nbr, employee). If ve vanl lo knov vhelhei lhe enpIoyees foi lhe
Iasl queiy do foin a conpIele lean, lhen:

DES> team(T,N) division (work(N,P,_) division work(smith,P,_))
As a caveal, nole lhal vaiialIes in lhe iighl opeiand of lhe division opeialoi aie
denanded if lhey occui in anolhei goaI, siniIai lo vhal happens vilh luiIl-ins as
conpaiison opeialois. Ioi inslance, lhe vaiialIe Y in lhe foIIoving queiy is denanded
and, lheiefoie, lhe queiy is nol vaIid:

DES> (t(X,Y) division s(Y)),p(Y)
y svilching lolh goaIs, lhe queiy lecones vaIid:

DES> p(Y),(t(X,Y) division s(Y))
If, on lhe conliaiy, Y does nol occui in any olhei sulgoaI (and in lhe head, if
consideiing a iuIe) lheie is no such denand iequiienenl. This issue lieaks lhe
decIaialive naluie of lhe division opeialoi. In addilion, lhis is nol vained lo lhe usei,
yel, and viII le pail of fuluie enhancenenls.


Fernando Senz-Prez 53/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.1.1% Integrity Constraints
Inlegiily consliainls aIIov lo specify vaIid vaIues foi lupIes in ieIalions. DLS
piovides seveiaI piedefined consliainls slenned fion SQL: lype, piinaiy key and
foieign key. In addilion, a piedefined funclionaI inlegiily consliainl is aIso piovided.
Useis can aIso define ils ovn inlegiily consliainls, vhich aie caIIed usei-defined
inlegiily consliainls fion nov on. AII of lhen can le decIaied and lhe syslen
nonilois lheii fuIfiInenl, vhich is lhe defauIl lehavioui. Hovevei, lhe connand
/check off aIIovs lo disalIe consliainl checking. AII piedefined inlegiily consliainls
appIy lo facls, lul lype consliainls, vhich aIso appIy lo iuIes. AIso, usei-defined
consliainls appIy lo facls and iuIes.
A conna-sepaialed sequence of piedefined inlegiily consliainls is aIIoved lo
specify nuIlipIe consliainls in a singIe inpul.
4.1.1%.1 Ay&e
A lype consliainl specifies lhe vaIues in a donain a piedicale aigunenl (lalIe
coIunn in ieIalionaI jaigon) nay lake. An exanpIe of lype consliainl decIaialion al lhe
connand pionpl is as foIIovs:

DES> :- type(p,[int,string])
This is equivaIenl lo lhe foIIoving aIleinalive synlax:

DES> :- type(p(int,string))
AIIoved lypes incIude lhe foIIoving (vheie each iov in lhe fiisl coIunn
conlains lype synonyns):

varchar
string
Sliing of unlounded Ienglh
char(N)
varchar(N)
Sliing vilh Ienglh up lo N
char
Sliing vilh Ienglh 1
integer
int
Inlegei nunlei
float
real
ReaI nunlei
Iiecision and iange depend on lhe undeiIying IioIog syslen.
Sulsequenl lype decIaialions aie aIIoved foi lhe sane piedicale and aiily, lhe
Iasl decIaialion is lhe one lo peisisl, oveiiiding pievious lype decIaialions foi such
piedicale. The foIIoving session is possilIe, and lhus lhe second decIaialion peisisls:

DES> :- type(p,[string,string])
DES> :- type(p,[int,int])
As veII, coIunns can le given nanes:



Fernando Senz-Prez 54/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> :- type(p,[a:int,b:string])
vhich is equivaIenl lo lhe foIIoving aIleinalive synlax:

DES> :- type(p(a:int,b:string))
Hovevei, a lype decIaialion foi a ieIalion aIieady lyped vilh a diffeienl aiily is
nol aIIoved. As viII le seen in fuilhei seclions, SQL slalenenls can iefei lo DalaIog
ieIalions, and SQL does nol aIIov ieIalions of lhe sane nane and diffeienl aiilies.

DES> :- type(p,[a:int])
Error: Cannot add types to a relation with several arities.
Relation: p
A DalaIog lype decIaialion is anaIogous lo lhe ciealion of an SQL lalIe, vilh
lhe sane oulcone (defining neladala foi a ieIalion: ieIalion nane, coIunn nanes and
lypes).

DES> /dbschema p
Info: Table:
* p(a:number(integer),b:string(varchar))

DES> drop table p

DES> /dbschema p
Info: No table or view found with that name.
DES> create table p(a int, b string)

DES> /dbschema p
Info: Table:
* p(a:number(integer),b:string(varchar))
Il is aIso possilIe lo onil coIunn nanes. In lhis case, lhey aie aulonalicaIIy
piovided (vilh nanes '$1','$2', and so on).

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

DES> /dbschema p
Info: Table:
* p($1:number(integer),$2:string(varchar))
Lel's considei lhe foIIoving session, vheie il can le seen lhal lhe syslen
nonilois lype consliainls in lolh DalaIog and SQL queiies:

DES> :-type(p,[int,string])
DES> /assert p(a,b)
Error: Type mismatch p.$1:number(integer) vs.
string(char(_6372)).
p($1:number(integer),$2:string(varchar))
DES> /assert p(1,a)
DES> p(X,Y)
{
p(1,a)
}
Info: 1 tuple computed.
DES> select * from p


Fernando Senz-Prez 55/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

answer(p.$1, p.$2) ->
{
answer(1,a)
}
Info: 1 tuple computed.
DES> insert into p values('a','b')
Error: Type mismatch p.$1:number(integer) vs.
string(char(_6937)).
p($1:number(integer),$2:string(varchar))
Info: 0 tuples inserted.
Nole lhal coIunns vilh aulonalicaIIy given nanes can le accessed fion an
SQL slalenenl, lul encIosed as speciaI usei idenlifieis. ISO deIinileis (doulIe quoles
"", suppoiled ly OiacIe and SQL Seivei) aie suppoiled as veII as olhei vendoi-specific
deIinileis: MS Access (squaie liackels |j) and MySQL (lack quoles ``). Olheivise, an
eiioi is iaised:

DES> select $1 from p
Error: Input processing error.

DES> select "$1" from p
answer(p.$1) ->
{
answer(1)
}
Info: 1 tuple computed.
A ieIalion aIieady defined is checked foi consislency vhen liying lo asseil a
nev lype consliainl:

DES> /assert t(1)
DES> /assert t(a)
DES> :-type(t,[int])
Error: No type tuple covers all the loaded rules for t/1:
t(1).
t(a).
Info: 2 rules listed.
ShouId any olhei consliainl ienains asseiled (olhei lhan a lype consliainl), a
lype consliainl cannol le changed:

DES> :-type(p,[a:int,b:string])
Error: Cannot change type assertion while other constraints
remain.
4.1.1%.1.1 Ay&es on Intensional Data*ase
Types can aIso le decIaied foi piedicales of lhe inlensionaI dalalase, i.e., lhose
piedicales defined al Ieasl vilh iuIes, nol onIy vilh facls. So, asseiling a nev lype
consliainl ovei an inlensionaI ieIalion viII liiggei lype checking, infeiiing lypes aIong
lhe piedicale dependency giaph iesliicled lo lhe lyped piedicale. Lel's considei lhe
foIIoving silualion as an exanpIe:

DES> /listing
s(a).
t(1).


Fernando Senz-Prez 56/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

t(X) :-
s(X).
Info: 3 rules listed.

DES> :-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.
4.1.1%.1.2 Ay&es on ?ro&ositional +elations
IinaIIy, pioposilionaI ieIalions aie aIso suljecl of leign lyped, of couise vilh an
enply Iisl of aigunenls:

DES> :-type(a,[])
DES> /dbschema a
Info: Table:
* a
The aIleinalive synlax lecones shoilei in lhis case indeed:

DES> :-type(a)

4.1.1%.2 1ulla*ility DE)istency ConstraintE
CoIunns can le inposed lo conlain a conciele vaIue ialhei lhan a nuII. The
nexl syslen session shovs an exanpIe:

DES> :-type(p,[a:int,b:string])
DES> :-nn(p,[a])
The Iisl of coIunn nanes specifies lhe coIunns foi vhich nuII vaIues aie nol
aIIoved. Thus, liying lo asseil a lupIe such as lhe foIIoving, viII iaise an eiioi:

DES> /assert p(null,'')
Error: Not null violation p.[a]
Sulsequenl exislency consliainls aie aIIoved foi lhe sane piedicale and aiily,
lhe Iasl decIaialion is lhe one lo peisisl, oveiiiding pievious decIaialions foi such
piedicale.
4.1.1%.3 ?rimary Fey
A piinaiy key consliainl specifies lhal no lvo lupIes have lhe sane vaIues foi a
given sel of coIunns. Nexl, a syslen session iIIusliales lhe use of a piinaiy key
asseilion:

DES> :-type(p,[a:int,b:string])
DES> :-pk(p,[a])
Iiinaiy key consliainls aie liiviaIIy salisfied vhen dupIicales aie disalIed, as
ieIalions aie consideied as sels, iiiespeclive of lhe cuiienl dalalase inslance, lhal nay
conlain dupIicales foi lhe aigunenls in lhe piinaiy key.


Fernando Senz-Prez 57/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

SeveiaI piinaiy key decIaialions aie aIIoved foi lhe sane piedicale and aiily,
lhe Iasl decIaialion is lhe one lo peisisl, oveiiiding pievious lype decIaialions foi such
piedicale:

DES> :-pk(p,[a])
DES> :-pk(p,[c])
Error: Unknown column c.
DES> :-pk(p,[a,a])
A ieIalion aIieady defined vilh facls oi iuIes is checked foi consislency vhen
liying lo asseil a nev piinaiy key consliainl:

DES> :-type(q,[a:int,b:int])
DES> /assert q(1,1)
DES> /assert q(2,2)
DES> /assert q(1,2)
DES> :-pk(q,[a])
Error: Primary key violation q.[a]
Offending values in database: [pk(1)]
Info: Constraint has not been asserted.
4.1.1%.4 Candidate Fey DUni8ueness ConstraintE
As a piinaiy key, a candidale key consliainl specifies lhal no lvo lupIes have
lhe sane vaIues foi a given sel of coIunns. Nexl, a syslen session iIIusliales lhe use of
a candidale key asseilion:

DES> :-type(p,[a:int,b:string])
DES> :-ck(p,[a])
Candidale key consliainls aie liiviaIIy salisfied vhen dupIicales aie disalIed,
as ieIalions aie consideied as sels, iiiespeclive of lhe cuiienl dalalase inslance, lhal
nay conlain dupIicales foi lhe aigunenls in lhe candidale key.
SeveiaI candidale key decIaialions aie aIIoved foi lhe sane piedicale and aiily.
y conliasl lo piinaiy keys, seveiaI candidale key consliainls aie aIIoved foi lhe sane
piedicale:

DES> :-ck(p,[b])
DES> :-ck(p,[a,b])
DES> /dbschema p
Info: Table:
* p(a:number(integer),b:string(varchar))
- NN: [a]
- CK: [a]
- CK: [b]
- CK: [a,b]
4.1.1%.% .oreign Fey
A foieign key consliainl specifies lhal lhe vaIues in a given sel of coIunns of a
ieIalion nusl exisl aIieady in lhe coIunns decIaied in lhe piinaiy key consliainl of
anolhei ieIalion. Nexl, an exanpIe of a foieign key asseilion is shovn:

DES> :-type(p(a:int)),type(q(b:int)),pk(q,[b])
DES> :-fk(p,[a],q,[b])


Fernando Senz-Prez 58/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Hovevei, if lhe ieIalions do nol exisl, an eiioi is iaised:

DES> :-fk(p,[a],q,[b])
Error: Relation p has not been typed yet.
DES> :-type(p,[a:int]), type(q,[b:int])
Tiying lo inpose a foieign key vilh a iefeienced lalIe vhich does nol have a
piinaiy key foi nalching coIunns iaises an eiioi:

DES> :-fk(p,[a],q,[b])
Error: Referenced column list q.[b] is not a primary key.
DES> :-pk(q,[b])
DES> :-fk(p,[a],q,[b])
The sane consliainl cannol le ieasseiled:

DES> :-fk(p,[a],q,[b])
Error: Trying to reassert an existing constraint.
DES> /dbschema
Info: Table(s):
* p(a:number(integer))
- FK: p.[a] -> q.[b]
* q(b:number(integer))
- PK: [b]
Info: No views.
DES> /assert p(1)
Error: Foreign key violation p.[a]->q.[b]
when trying to insert: p(1)
DES> /assert q(1)
DES> /assert p(1)
DES> /listing
p(1).
q(1).
Info: 2 rules listed.
SeveiaI foieign keys nay exisl foi lhe sane ieIalion:

DES> :-type(p,[a:int])
DES> :-type(q,[b:int])
DES> :-type(r,[a:int,b:int,c:string])
DES> :-pk(p,[a]), pk(q,[b])
DES> :-fk(r,[a],p,[a]), fk(r,[b],q,[b])
DES> /dbschema r
Info: Table:
* r(a:number(integer),b:number(integer),c:string(varchar))
- FK: r.[a] -> p.[a]
- FK: r.[b] -> q.[b]
Refeienced coIunns have lo nalch lhe lypes of foieign key coIunns, olheivise
an eiioi is iaised:

DES> :-fk(r,[c],q,[b])
Error: Type mismatch r.c:string(varchar) <> q.b:number(integer)
A ieIalion aIieady defined vilh facls oi iuIes is checked foi consislency vhen
liying lo asseil a nev foieign key consliainl:


Fernando Senz-Prez 5/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


DES> :-type(p,[a:int])
DES> :-type(q,[a:int])
DES> /assert p(1)
DES> :-pk(q,[a])
DES> :-fk(p,[a],q,[a])

Error: Foreign key violation p.[a]->q.[a]
Offending values in database: [fk(1)]
Info: Constraint has not been asserted.
4.1.1%." .unctional De&endency
A funclionaI dependency consliainl specifies lhal, given a sel of alliilules A1 of
a ieIalion R, lhey funclionaIIy deleinine anolhei sel A2, i.e., each lupIe of vaIues of A1
in R is associaled vilh pieciseIy one lupIe of vaIues A2 in lhe sane lupIe of R.

DES> :-fd(p,[a],[c])
Error: Relation p has not been typed yet.
DES> :-type(p,[a:int,b:int])
DES> :-fd(p,[a],[c])
Error: Unknown column c.
DES> :-fd(p,[a],[b])
DES> /dbschema p
Info: Table:
* p(a:number(integer),b:number(integer))
- FD: [a] -> [b]
y asseiling lhe facl p(1,2), il nusl hoId lhal any olhei lupIe vilh 1 in ils fiisl
alliilule nusl have lhe vaIue 2 in ils second alliilule.

DES> /assert p(1,2)
DES> /assert p(1,3)
Error: Functional dependency violation p.[a]->p.[b]
in table p(a,b)
when trying to insert: p(1,3)
Witness tuple : p(1,2)
SeveiaI funclionaI dependency consliainls can le inposed on a given ieIalion.
They can le deIeled eilhei vilh lhe connand drop_ic oi vhen an SQL DROP TABLE
oi DROP DATABASE slalenenls aie issued.
TiiviaI funclionaI dependencies aie iejecled:

DES> :-fd(p,[a],[a])
Warning: Trivial functional dependency. Not asserted.
A ieIalion aIieady defined vilh facls oi iuIes is checked foi consislency vhen
liying lo asseil a nev funclionaI dependency consliainl:

DES> :-type(p,[a:int,b:int,c:int])
DES> /assert p(1,1,1)
DES> /assert p(1,2,3)
DES> :-fd(p,[a],[c])
Error: Functional dependency violation p.[a]->p.[c]
Offending values in database: [fd(1,1,1),fd(1,2,3)]


Fernando Senz-Prez 6!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Info: Constraint has not been asserted.
4.1.1%.( UserGde:ined Integrity Constraints
Useis can aIso define lheii ovn inlegiily consliainls. A usei-defined inlegiily
consliainl is iepiesenled vilh a iuIe vilhoul head. The iuIe lody is an asseilion lhal
specifies inconsislenl dala, i.e., shouId lhis lody can le pioved, an inconsislency is
delecled and iepoiled lo lhe usei.
DecIaiing such inlegiily consliainls inpIies lo change youi nind v.i.l. usuaI
consislency consliainls as donain consliainls in SQL. Ioi inslance, lo specify lhal a
coIunn c of a lalIe t can lake vaIues lelveen lvo inlegeis one can use lhe SQL cIause
CHECK in lhe ciealion of lhe lalIe as foIIovs
4
:

CREATE TABLE t(c INT CHECK (c BETWEEN 0 AND 10));
In conliasl, in DalaIog you can sulnil lhe foIIoving consliainls:

DES> :-type(t,[c:int])
DES> :-t(X),(X<0;X>10)
Nolice lhal lhe iuIe lody succeeds foi vaIues in t oul of lhe inleivaI |0,10j. So,
an inlegiily consliainl specifies unfeasible vaIues ialhei lhan feasilIe. AIso nole lhal
vhiIsl seveiaI piedefined consliainls aie aIIoved in a consliainl, onIy one usei-defined
inlegiily consliainl is aIIoved. A coupIe of asseilions lo shov lhe lehavioui of lhe
alove exanpIe foIIov:

DES> /assert t(0)
DES> /assert t(11)
Error: Integrity constraint violation.
ic(X) :-
t(X),
X < 0
;
X > 10.
Offending values in database: [ic(11)]
Nole lhal lo le alIe lo inleipiel lhal offending vaIues, lhe inlegiily consliainl is
shovn as a iuIe defining a nev piedicale ic, vheie lhe iuIe's head has as nany
vaiialIes as ieIevanl vaiialIes in lhe consliainl. Then, offending vaIues aie
encapsuIaled in lhe neaning of lhe consliainl ieIalion ic.
A iuIe lody of a consliainl is any vaIid iuIe lody, i.e., goaIs in consliainsls can
iefei lo olhei usei-defined oi luiIl-in piedicales as veII, incIuding negalion,
aggiegales, elc. Lel's considei lhe foIIoving session, in vhich ve aie inleiesled in
specifying a diiecled liee (a connecled giaph vilh no cycIes):

DES> /verbose on
Info: Verbose output is on.
DES> /consult paths
Info: Consulting paths...
edge(a,b).
edge(a,c).

4
This CHECK SQL cIause is nol yel suppoiled ly DLS.


Fernando Senz-Prez 61/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

edge(b,a).
edge(b,d).
path(X,Y) :-
path(X,Z),
edge(Z,Y).
path(X,Y) :-
edge(X,Y).
end_of_file.
Info: 6 rules consulted.
Info: Computing predicate dependency graph...
Info: Computing strata...
DES> :-path(X,X)
Info: Parsing query...
Info: Constraint successfully parsed.
Info: Checking user-defined integrity constraint over database.
:-
path(X,X).
Info: Computing predicate dependency graph...
Info: Computing strata...
Error: Integrity constraint violation.
ic(X) :-
path(X,X).
Offending values in database: [ic(b),ic(a)]
Info: Constraint has not been asserted.
The consliainl :-path(X,X) specifies lhal a palh fion a node lo ilseIf is nol
aIIoved. As lhe consuIled piogian conlains a cycIe invoIving nodes a and b, lhe
consliainl is vioIaled and lheiefoie il is nol asseiled. Offending vaIues aie Iisled (in
lhis case, aII lhe vaIues invoIved in any cycIe, you can liy oul olhei edges and see lhe
oulcone).
Anolhei use is lo fiisl specify lhe consliainl and lhen a giaph. Hovevei, don'l
le lenpled lo sulnil lhe consliainl and consuIl lhe piogian: lhe consliainl viII le
ienoved since consuIling a piogian anounls lo eiase lhe exisling dalalase, incIuding
usei-defined inlegiily consliainls. Inslead, use lhe reconsult connand:

DES> /verbose on
Info: Verbose output is on.
DES> /cd examples
Info: Current directory is:
c:/fernan/research/bddeduc/des/des3.4/examples/
DES> :-path(X,X)
Info: Parsing query...
Info: Constraint successfully parsed.
Info: Checking user-defined integrity constraint over database.
:-
path(X,X).
Info: Computing predicate dependency graph...
Warning: Undefined predicate(s): [path/2]
Info: Computing strata...
DES> /reconsult paths
Info: Consulting paths...
edge(a,b).
edge(a,c).


Fernando Senz-Prez 62/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

edge(b,a).
edge(b,d).
Info: Checking user-defined integrity constraint over database.
:-
path(X,X).
Info: Computing predicate dependency graph...
Info: Computing strata...
path(X,Y) :-
path(X,Z),
edge(Z,Y).
Info: Checking user-defined integrity constraint over database.
:-
path(X,X).
Info: Computing predicate dependency graph...
Info: Computing strata...
Error: Integrity constraint violation.
ic(X) :-
path(X,X).
Offending values in database: [ic(b),ic(a)]
path(X,Y) :-
edge(X,Y).
File :
c:/fernan/research/bddeduc/des/des3.4/examples/paths.dl
Lines: 10,10
end_of_file.
Info: 5 rules consulted.
Info: Computing predicate dependency graph...
Info: Computing strata...
Nole lhal lhe fiisl iuIe foi path is nol iejecled since in lhe aIieady consuIled
piogian il is sliII consislenl v.i.l. lo lhe consliainl. Hovevei, liying lo add lhe second
iuIe foi path nakes il infeasilIe, so lhal il is iejecled. Nov, onIy 5 iuIes have leen
asseiled. If lhe fiIe vas nol incIuded lhe lhiid facl foi edge, lhen il vouId le accepled
as a vaIid liee. Again, liying lo inseil such a lupIe, aflei such a piogian is consuIled,
iaises an eiioi:

DES> /assert edge(d,a)
Info: Checking user-defined integrity constraint over database.
:-
path(X,X).
Info: Computing predicate dependency graph...
Info: Computing strata...
Error: Integrity constraint violation.
ic(X) :-
path(X,X).
Offending values in database: [ic(a),ic(b),ic(d)]
Olseive lhal since lhe path ieIalion is nov conpIele, aII lhe nodes in lhe cycIe
aie dispIayed (a, b, and c).
The consideied consliainl is nol yel enough lo ensuie a diiecled liee defined ly
edge facls. Tvo condilions ienain: Iiisl, a given node cannol have noie lhan one
inconing edge, and, second, a liee nusl le a connecled giaph. If lhe fiisl condilion is
inposed, il suffices foi lhe second lo check lhal lhe nunlei of nodes is lhe nunlei of
edges pIus 1. So:


Fernando Senz-Prez 63/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


DES> /assert node(N):-edge(N,A);edge(A,N)
Info: Computing predicate dependency graph...
Info: Computing strata...
Info: Rule asserted.
DES> :-count(edge(A,B),Es), count(node(N),Ns), D is Ns-Es, D\=1.
Info: Parsing query...
Info: Constraint successfully parsed.
Info: Computing predicate dependency graph...
Info: Computing strata...
Info: Checking user-defined integrity constraint over database.
:-
count(edge(A,B),Es),
count(node(N),Ns),
D is Ns - Es,
D \= 1.
Info: Computing by stratum of [edge(A,B),node(A)].
Info: Computing predicate dependency graph...
Info: Computing strata...
DES> /assert edge(e,f) % An unconnected component
Info: Checking user-defined integrity constraint over database.
:-
count(edge(A,B),Es),
count(node(N),Ns),
D is Ns - Es,
D \= 1.
Info: Computing by stratum of [edge(A,B),node(A)].
Info: Computing predicate dependency graph...
Info: Computing strata...
Error: Integrity constraint violation.
ic(Es,Ns,D) :-
count(edge(A,B),Es),
count(node(N),Ns),
D is Ns - Es,
D \= 1.
Offending values in database: [ic(4,6,2)]
Usei-defined inlegiily consliainls aie diopped vhen aloIishing lhe dalalase oi
consuIling a fiIe.
4.1.1%.8 Dro&&ing Constraints
Any piedefined oi usei-defined inlegiily consliainl can le diopped vilh lhe
connand /drop_ic (see Seclion 5.14.1) foIIoved ly lhe consliainl lo le diopped vilh
lhe sane synlax as ils decIaialion.
4.1.1%. Ca0eats
Lilhei ly consuIling a piogian, oi ly diopping lhe cuiienl dalalase, oi ly
aloIishing lhe dalalase, aII inlegiily consliainls aie ienoved, incIuding SQL lalIe and
viev definilions.
As iuIes aie nol checked foi piedefined consliainls, a silualions Iike lhe
foIIoving nay occui:

DES> create table t(a int primary key)


Fernando Senz-Prez 64/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> insert into t values (1)
Info: 1 tuple inserted.
DES> /assert t(X):-X=1
DES> /duplicates on
DES> t(X)
{
t(1),
t(1)
}
Info: 2 tuples computed.
NonelheIess, if you aIso vanl lo noniloi iuIes, you can olheivise use a usei-
defined consliainl such as:

DES> create table t(a int)
DES> insert into t values (1)
Info: 1 tuple inserted.
DES> :-group_by(t(X),[X],C=count(X),C>1),C>1
DES> /assert t(X):-X=1
Error: Integrity constraint violation.
ic(X,C) :-
group_by(t(X),[X],(C = count(X),C > 1)),
C > 1.
Offending values in database: [ic(1,2)]
Error: Asserting rules due to integrity constraint violation.
4.1.1" @y&ot/etical #ueries
HypolhelicaI queiies aie a connon need in seveiaI scenaiios, ieIaled nainIy
vilh lusiness inleIIigence appIicalions and lhe Iike. They aie aIso knovn as "vhal-if"
queiies and heIp nanageis lo lake decisions on scenaiios vhich aie sonevhal
changed vilh iespecl lo a cuiienl slale. Such queiies aie used, foi inslance, foi
deciding vhich iesouices nusl le added, changed oi ienoved lo oplinize sone
ciileiiun (cosl funclion - aIso veII ieIaled lo oplinizalion lechnoIogies). HypolhelicaI
queiies in lhe dalalase aiena aie lypicaIIy used foi assunplions v.i.l. a cuiienl
dalalase inslance.
DLS incIudes one foin of hypolhelicaI DalaIog queiies vhich nay seive lo
ansvei seveiaI queslions. The synlax of an hypolhelicaI queiy is as foIIovs:

Rule1 /\ ... /\ RuleN => Goal
vhich neans lhal, assuning lhal lhe cuiienl dalalase is augnenled vilh lhe iuIes
Rule1, ..., RuleN, lhen Goal is conpuled vilh iespecl lo lhe cuiienl dalalase vhich is
augnenled vilh lhese iuIes, vhich nusl le safe (see Seclion 5.3). Such queiy is aIso
undeisland as a IileiaI in lhe conlexl of a iuIe, so lhal any iuIe can conlain hypolhelicaI
goaIs, as in a :- b => c. In luin, any Rulei can conlain hypolhelicaI goaIs.
VaiialIes in Rulei aie IocaI lo Rulei (i.e., lhey aie neilhei shaied vilh olhei iuIes noi
lhe goaI). Moieovei, a hypolhelicaI IileiaI does neilhei shaie vaiialIes vilh olhei
IileiaIs noi lhe head of lhe iuIe in vhich il occuis.


Fernando Senz-Prez 65/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

oiioving an exanpIe fion |on9Oj
5
, ve considei an exlended and adapled
iuIe-lased syslen foi desciiling univeisily poIicy: student(S) neans lhal S is a
sludenl, course(C) lhal C is a couise, take(S,C) lhal sludenl S lakes couise C, and
grad(S) lhal S is eIigilIe foi giadualion. The exlensionaI dalalase can conlain facls
as:

student(adam).
student(bob).
student(pete).
student(scott).
student(tony).

course(eng).
course(his).
course(lp).

take(adam,eng).
take(pete,his).
take(pete,eng).
take(scott,his).
take(scott,lp).
take(tony,his).
The inlensionaI dalalase can conlain iuIes as:

grad(S) :- take(S,his), take(S,eng).
A ieguIai queiy foi sludenls lhal vouId le eIigilIe lo giaduale is:

DES> grad(S)
{
grad(pete)
}
Info: 1 tuple computed.
A fiisl hypolhelicaI queiy foi lhis dalalase asks "If Tony look eng, vouId he
le eIigilIe lo giaduale`", vhich can le queiied vilh:

DES> take(tony,eng) => grad(tony)
Info: Processing:
answer :-
take(tony,eng)=>grad(tony).
{
answer
}
Info: 1 tuple computed.
Moie lhan one assunplion can le sinuIlaneousIy slaled, as in: "If Tony look
eng, and Adan look his, vhal aie lhe sludenls lhal aie eIigilIe lo giaduale`"


5
Hovevei, nole lhal oui appioach diffeis fion |on9Oj in al Ieasl lhe foIIoving: ve
aIIov foi iuIes in lhe assunplion (nol onIy facls), an assuned facl shouId nol le unsafe, and ve
do nol aIIov assuning negalive infoinalion (yel!)


Fernando Senz-Prez 66/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> take(tony,eng) /\ take(adam,his) => grad(S)
Info: Processing:
answer(S) :-
take(tony,eng)/\take(adam,his)=>grad(S).
{
answer(adam),
answer(pete),
answer(tony)
}
Info: 3 tuples computed.
Anolhei queiy is "Which aie lhe sludenls vhich vouId le eIigilIe lo giaduale if
his and lp veie enough lo gel il`":

DES> (grad(S) :- take(S,his), take(S,lp)) => grad(S)
Info: Processing:
answer(S) :-
(grad(S):-take(S,his),take(S,lp))=>grad(S).
{
answer(pete),
answer(scott)
}
Info: 2 tuples computed.
Nole lhal, aIlhough S occuis in lolh lhe anlecedenl and lhe consequenl, lhey
aie nol acluaIIy shaied, and lhey sinpIy acl as diffeienl vaiialIes.
Consideiing aIso infoinalion aloul couise pieiequisiles as:

pre(eng,lp).
pre(hist,eng).
pre(Pre,Post) :-
pre(Pre,X),
pre(X,Post).
One nighl vondei vhelhei adding a nev pieiequisile inpIies a cycIe (so lhal
sludenls cannol fuIfiI pieiequisiles al aII foi lhe couises in a cycIe):

DES> pre(lp,hist)=>pre(X,X)
Info: Processing:
answer(X) :-
pre(lp,hist)=>pre(X,X).
{
answer(eng),
answer(hist),
answer(lp)
}
Info: 3 tuples computed.
The ansvei incIudes lhose nodes in lhe giaph lhal aie in a cycIe.
4.1.1".1 @y&ot/etical #ueries and Integrity Constraints
Assunplions can le used in conlinalion vilh any of lhe fealuies of DLS, in
pailicuIai, inlegiily consliainls. IoIIoving lhe pievious exanpIe, you can even expiess
il vilh lhe aid of inlegiily consliainls. Avoiding cycIes can le foiced ly:



Fernando Senz-Prez 67/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> :-pre(X,X)
Then, if you vanl lo Iisl pieiequisiles assuning pre(lp,hist) as lefoie:

DES> pre(lp,hist)=>pre(X,Y)
Info: Processing:
answer(X,Y) :-
pre(lp,hist)=>pre(X,Y).
Error: Integrity constraint violation.
ic(X) :-
pre(X,X).
Offending values in database: [ic(lp),ic(eng),ic(hist)]
Info: The following rule cannot be assumed:
pre(lp,hist).
{
answer(eng,lp),
answer(hist,eng),
answer(hist,lp)
}
Info: 3 tuples computed.
So, lhe syslen infoins lhal lheie is an inconsislency vhen liying lo asseil such
offending facl (pre(lp,hist)), vhich nakes pieiequisiles lo foin a cycIe (as shovn
in lhe offending vaIue Iisl [ic(lp),ic(eng),ic(hist)]). The syslen infoins
aloul lhe iuIes lhal cannol le assuned lul conlinues ils piocessing. This is aIso usefuI
lo knov lhe iesuIl foi lhe adnissilIe assunplions. Nole lhal, in geneiaI, offending
facls can le a sulsel of lhe neaning of an assuned iuIe in lhe conlexl of lhe cuiienl
dalalase. To iIIusliale lhis, Iel's considei lhe foIIoving piogian foi lhioving a coin:

% Tails win:
:- win, heads.

win :- heads ; tails.
Iiedicale win slales lhal one vins if eilhei heads oi laiIs aie gol, and lhe
consliainl slales lhal you have lo gel laiIs lo vin. Then, lhe foIIoving hypolhelicaI goaI
slales vhelhei assuning heads oi laiIs Ieads lo vin.

DES> heads /\ tails => win
Info: Processing:
answer :-
heads/\tails=>win.
Error: Integrity constraint violation.
ic :-
win,
heads.
Info: The following rule cannot be assumed:
heads.
{
answer
}
Info: 1 tuple computed.
As infoined, heads cannol le assuned in oidei lo vin.


Fernando Senz-Prez 68/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.1.1".2 @y&ot/etical #ueries and Du&licates
DupIicales can aIso le used aIong conpulalions invoIving assunplions. Lel's
considei a vaiialion of lhe cIassicaI Nin gane, knovn as lhe sulliaclion gane. Heie,
lheie is onIy one heap fion vhich a pIayei can lake one oi lvo lokens in his luin. A
pIayei vins if lheie is onIy one loken in olhei pIayei's luin (misre gane). This can le
foinuIaled vilh lhe nexl piogian:

win_nim :-
take => one_left.
win_nim :-
take/\take => one_left.
win_nim :-
take => enough, win_nim.
win_nim :-
take/\take => enough, win_nim.

one_left :-
total(N),
count(take,C),
N-C=1.

enough :-
total(N),
count(take,C),
N-C>0.

total(4).
The piedicale win_nim slales lhal I vin if I lake one oi lvo lokens and lheie is
one Iefl foi you. Olheivise, if lheie aie enough lokens (aflei laking one oi lvo) lo
conlinue pIaying, lhen Iel's see if I can vin.
Lach occuiience of take in lhe Iefl hand side of => is an assuned facl lhal can
le counled if dupIicales aie enalIed (olheivise, lhe counling viII le O - if lheie is no
one - oi 1 - if lheie is one oi noie, as dupIicales aie discaided). So, lhe piedicale
one_left deleinines vhelhei lheie is exaclIy one loken Iefl, and enough deleinines
if lheie is one loken Iefl al Ieasl. The piedicale total slales lhe lolaI nunlei of lokens
vhich aie avaiIalIe foi a gane.
Ioi noie lhan 2 lokens lheie is aIvays lolh vinning and Ioosing palhs foi lhe
pIayei in luin. Ioi exaclIy 2 lokens lheie is no Ioosing palh (lecause lhe pIayei cannol
lake 2 as lhe heap vouId le enply). And foi 1 loken, lheie is no vinning palh:

DES> win_nim
{
}
Info: 0 tuples computed.
Nole lhal enalIing dupIicales can Iead lo non-leininaling queiies. Ioi inslance,
Iel's considei:

DES> /duplicates off
DES> /assert p:-p=>p
DES> p


Fernando Senz-Prez 6/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

{
p
}
Info: 1 tuple computed.
DES> /duplicates on
DES> p
... Non-terminating
Heie, lhe hypolhesis p is iecuisiveIy added lo lhe dalalase vilh no end as lheie
is no leininaling condilion.
4.1.1".3 @y&ot/etical #ueries and 1egation
InpIicalion can aIso le used in conjunclion vilh negalion. Lel's considei lhe
foIIoving exanpIe, vhich slales fIighl Iinks (flight/2 foi oiigin and deslinalion)
lelveen aiipoils (aiipoil), and vheie fIighl liaveIs (flight_travel/2 aIso foi
oiigin and deslinalion) aie possilIe if invoIved aiipoils aie nol cIosed:

flight_travel(X,Y) :-
flight(X,Y),
not(closed(X)),
not(closed(Y)).
flight_travel(X,Y) :-
flight_travel(X,Z),
flight_travel(Z,Y).

flight(a,b).
flight(b,c).
flight(c,d).
A ieguIai queiy foi consuIling possilIe liaveIs is:

DES> flight_travel(X,Y)
{
flight_travel(a,b),
flight_travel(a,c),
flight_travel(a,d),
flight_travel(b,c),
flight_travel(b,d),
flight_travel(c,d)
}
Info: 6 tuples computed.
Assuning lhal aiipoil b is cIosed, ve ask foi lhe possilIe liaveIs vilh lhis
assunplion:

DES> closed(b) => flight_travel(X,Y)
Info: Processing:
answer(X,Y) :-
closed(b)=>flight_travel(X,Y).
{
answer(c,d)
}
Info: 1 tuple computed.
vheie negaled caIIs lo closed/1 occui in lhe fiisl iuIe of flight_travel/2.


Fernando Senz-Prez 7!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

We can aIso ask foi lhe opposile: Which aie lhe fIighl liaveIs vhich aie nol
possilIe foi lhal assunplion:

DES> flight_travel(X,Y),(closed(b)=>not(flight_travel(X,Y)))
Info: Processing:
answer(X,Y) :-
flight_travel(X,Y),
closed(b)=>not(flight_travel(X,Y)).
{
answer(a,b),
answer(a,c),
answer(a,d),
answer(b,c),
answer(b,d)
}
Info: 5 tuples computed.
Nole lhal, fiisl, ve ask foi aII lhe possilIe fIighls (fiisl goaI
flight_travel(X,Y)) and, lhen, ve iesliicl lo lhose fIighls vhich aie nol possilIe
undei lhe assunplion. The fiisl goaI is needed foi lhe queiy lo le safe. RecaII lhal
DalaIog vilh negalion is nol consliuclive (vaiialIes in lhe negaled goaI aie nol
inslanlialed unIess lheii vaIues aie aIieady piovided ly a posilive goaI), and ansveis
nusl le giound. Nole, aIso, lhal lhe neaning of lhe fiisl occuiience of goaI
flight_travel(X,Y) in lhis Iasl queiy is lhe veiy sane as lhe neaning of lhe fiisl
queiy. Hovevei, lhe neaning of lhe second occuiience of lhal goaI iesliicls lhe ansvei
lo lhose fIighls foi vhich invoIved aiipoils aie nol cIosed lecause of lhe assunplion.
4.2 S#$
The synlax iecognized ly lhe inleipielei is loiioved fion lhe SQL slandaid.
This seclion desciiles lhe nain Iinilalions, fealuies, and decisions laken in designing
SQL, vhich coexisls vilh DalaIog. AIso, ve desciile lhe foui pails of lhe suppoiled
sulsel of lhe SQL Ianguage: DDL (Dala Definilion Language, foi defining lhe dalalase
schena), DQL (Dala Queiy Language, foi Iisling conlenls of lhe dalalase) and DML
(Dala ManipuIalion Language, foi inseiling and deIeling lupIes), and ISL (Infoinalion
Schena Language). Seclion 4.2.8 iesunes lhe SQL giannai. As ODC conneclions aie
aIIoved, sone DMS specific fealuies have leen added, as veII as non-slandaid
fealuies in ISL.
4.2.1 Main $imitations
The piojeclion Iisl consisls of coIunn iefeiences (column, table.column,
alias.column), viIdcaids (*, table.*, alias.*), aIias iefeiences, aiilhnelic
expiessions and SQL slalenenls. Olhei expiessions nighl le suppoiled in fuilhei
ieIeases.
A Iiniled coveiage of dalalase inlegiily consliainls.
Sliong lyping. Diffeienl nuneiic lype vaIues cannol le conpaied (e.g., ieaI and
inlegei). AIso, lheie is no piovision foi aulonalic lype casling
No inseilions/deIelions/updales inlo vievs.


Fernando Senz-Prez 71/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Liniled synlax eiioi iepoils. The paisei does nol infoin aloul aII lhe possilIe
synlax eiioi causes, lul foi lalIe, viev and coIunn nisspeIIed nanes. Hovevei,
synlax eiiois fion ODC conneclions aie dispIayed.
4.2.2 Main .eatures
As nain fealuies, ve highIighl:
Dala queiy, dala definilion, and dala nanipuIalion Ianguage pails piovided.
Sulqueiies (nesled queiies vilhoul deplh Iinils).
CoiieIaled queiies (lalIes and ieIalions in nesled sulqueiies can le iefeienced ly
lhe hosl queiy). Ioi exanpIe: SELECT * FROM t,(SELECT a FROM s) WHERE
t.a=s.a.
Sulqueiies in conpaiisons, as SELECT a FROM t WHERE t.a > (SELECT a
FROM s).
TalIe, ieIalion, and expiession aIiases vilh fuII scope.
Suppoil foi dupIicales and dupIicale eIininalion
Non-Iineai iecuisive queiies.
Recuisive queiies aie nol iesliicled v.i.l. aggiegales oi nesled conpulalions as
usuaI RDMS's aie (IM D2, MS SQL Seivei, SUN OiacIe, MySQL, ...)
SinpIified iecuisive queiies aie aIIoved: AIlhough suppoiled, lheie is no need foi
using a WITH cIause
HypolhelicaI queiies, vhich aie a noveI pioposaI oul of lhe slandaid
Sel opeialois luiId ieIalions, vhich can le used vheievei a dala souice is expecled
(FROM cIause).
NuII vaIues aie suppoiled, aIong vilh oulei joins (fuII, Iefl and iighl).
Aggiegale funclions aIIoved in expiessions al lhe piojeclion Iisl and HAVING
condilions. GROUP BY cIauses aie aIso aIIoved.
Viev suppoil. Any ieIalion luiIl vilh an SQL queiy can le defined as a viev (even
iecuisive queiies).
Suppoiled dalalase inlegiily consliainls incIude lype consliainls, exislency
(nuIIaliIily), piinaiy keys, candidale keys, and iefeienliaI inlegiily consliainls.
Iaienlheses can le used eIsevheie lhey aie needed and aIso foi easing lhe ieading
of slalenenls.
Suggeslions aie piovided foi nisspeIIed lalIe, viev and coIunn nanes vhen
siniIai enliies aie found
4.2.3 Datalog 0s. S#$
Wilh iespecl lo DalaIog, sone decisions have leen laken:
As in DalaIog, usei idenlifieis aie case-sensilive (lalIe and alliilule nanes, ...). This
is nol lhe noinaI lehavioui of cuiienl ieIalionaI dalalase syslens.


Fernando Senz-Prez 72/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

In conliasl lo DalaIog, luiIl-in idenlifieis aie nol case-sensilive. This confoins lo
lhe noinaI lehavioui of cuiienl ieIalionaI dalalase syslens.
4.2.4 Data De:inition $anguage
This pail of lhe Ianguage deaIs vilh ciealing (oi iepIacing), and diopping lalIes
and vievs. Theie is no piovision foi updaling lhe schena, vhich can le consuIled vilh
lhe connand /dbschema.
4.2.4.1 Creating Aa*les
The fiisl foin of lhis slalenenl is as foIIovs:

CREATE [OR REPLACE] TABLE TableName(Column1 Type1
[ColumnConstraint1], ..., ColumnN TypeN [ColumnConstraintN] [,
TableConstraints])
This slalenenl defines lhe lalIe schena vilh nane TableName and coIunn
nanes Column1, ..., ColumnN., vilh lypes Type1, ..., TypeN, iespecliveIy. If lhe
oplionaI cIause OR REPLACE is used, lhe lalIe is diopped if exisled aIieady, deIeling
aII of ils lupIes.
A second foin of lhis slalenenl aIIovs lo cieale a lalIe vilh lhe sane schena
of an exisling lalIe, foIIoving SQL slandaid oplionaI fealuie T171:

CREATE TABLE TableName ( LIKE ExistingTableName )
Iaienlheses aie nol nandaloiy, lhough. This veision copies lhe conpIele
schena, incIuding aII inlegiily consliainls (lolh piedefined and usei-defined).
Theie is piovision foi seveiaI coIunn consliainls:
NOT NULL. Lxislency consliainl foiliding nuII vaIues
PRIMARY KEY. Iiinaiy key consliainl foi onIy one coIunn
UNIQUE. Uniqueness consliainl foi onIy one coIunn (AIso aIIoved lhe aIleinalive
synlax: CANDIDATE KEY)
REFERENCES TableName[(Column)]. RefeienliaI inlegiily consliainl foi onIy
one coIunn
DETERMINED BY Column. IunclionaI dependency. If lhis consliainl is appIied lo
lhe coIunn Column1, lhen: Column Column1
Check consliainls aie nol suppoiled in lhis synlax up lo nov. Hovevei, lhey
can le inposed via DalaIog usei-defined consliainls as expIained in Seclion 4.1.15.7.
AIso, lheie is piovision foi seveiaI lalIe consliainls:
PRIMARY KEY (Column,..., Column) . Iiinaiy key consliainl foi one oi
noie coIunns
UNIQUE (Column,..., Column) . Uniqueness consliainl foi one oi noie
coIunns (AIso aIIoved lhe non-slandaid aIleinalive synlax: CANDIDATE KEY
(Column,..., Column) )
FOREIGN KEY (Column1,..., ColumnN) REFERENCES
TableName[(Column1,..., ColumnN)] )]. RefeienliaI inlegiily consliainl
foi one oi noie coIunns
CHECK (CheckConstraint). Check consliainl, as Iisled nexl
Check consliainls:


Fernando Senz-Prez 73/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Condition. As in a WHERE cIause
(ColumnR1,..., ColumnRN) DETERMINED BY (ColumnL1,...,
ColumnLN). IunclionaI dependency: ColumnL1,...,ColumnLN
ColumnR1,...,ColumnRN
AIIoved lypes incIude:
CHAR. Iixed-Ienglh sliing of 1
CHAR(n). Iixed-Ienglh sliing of n chaiacleis
VARCHAR(n). VaiialIe-Ienglh sliing of up lo n chaiacleis
VARCHAR (oi STRING). VaiialIe-Ienglh sliing of up lo lhe naxinun Ienglh of lhe
undeiIying IioIog alon
INTEGER (oi INT) . Inlegei nunlei
REAL. ReaI nunlei
LxanpIes:

CREATE TABLE t(a INT PRIMARY KEY, b STRING)

CREATE OR REPLACE TABLE s(a INT, b INT REFERENCES t(a), PRIMARY
KEY (a,b))
Nole in lhis Iasl exanpIe lhal if lhe coIunn nane in lhe iefeienliaI inlegiily
consliainl is nissing, lhe iefeiied coIunn of lalIe t is assuned lo have lhe sane nane
lhal lhe coIunn of s vheie lhe consliainl appIies (i.e., b). So, an eiioi is lhiovn
lecause coIunns s.b and t.b have diffeienl lypes:

DES-SQL> CREATE OR REPLACE TABLE s(a INT, b INT REFERENCES t,
PRIMARY KEY (a,b))

Error: Type mismatch s.b:number(int) <> t.b:string(varchar).
Error: Imposing constraints.
A decIaied piinaiy key oi foieign key consliainl is checked vhenevei a nev
lupIe is added lo a lalIe, foIIoving ieIalionaI dalalases. Nole lhal asseilion of iuIes
fion lhe DalaIog side aie aIIoved lul nol checked. A DalaIog iuIe shouId le vieved as
a conponenl of lhe inlensionaI dalalase. RDs avoid lo define a viev vilh lhe sane
nane as a lalIe and, lheiefoie, lheie is no vay of unexpecled lehaviouis such as lhe
iIIuslialed leIov:

DES-SQL> create or replace table t(a int, b int, c int, d int,
primary key (a,c))

DES-SQL> insert into t values(1,2,3,4)
Info: 1 tuple inserted.

DES-SQL> % The following is expected to raise an error:

DES-SQL> insert into t values(1,1,3,4)
Error: Primary key violation when trying to insert: t(1,1,3,4)
Info: 0 tuples inserted.



Fernando Senz-Prez 74/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES-SQL> % However, the following is allowed:

DES-SQL> /assert t(X,Y,Z,U) :- X=1,Y=2,Z=3,U=4.

DES-SQL> /listing
t(1,2,3,4).
t(X,Y,Z,U) :-
X = 1,
Y = 2,
Z = 3,
U = 4.
Iioduclion iuIes (i.e., lhose defining lhe inlensionaI dalalase) aie nol checked
foi piinaiy key and foieign key consliainls.
Nexl, a veiy sinpIe exanpIe is iepioduced lo iIIusliale lasic consliainl
handIing:

DES-SQL> create or replace table u(b int primary key,c int)

DES-SQL> create or replace table s(a int,b int, primary key
(a,b))

DES-SQL> create or replace table t(a int,b int,c int,d int,
primary key (a,c), foreign key (b,d) references s(a,b), foreign
key(b) references u(b))

DES-SQL> insert into t values(1,2,3,4)
Error: Foreign key violation t.[b,d]->s.[a,b] when trying to
insert: t(1,2,3,4)
Info: 0 tuples inserted.

DES-SQL> insert into s values(2,4)
Info: 1 tuple inserted.

DES-SQL> insert into t values(1,2,3,4)
Error: Foreign key violation t.[b]->u.[b] when trying to insert:
t(1,2,3,4)
Info: 0 tuples inserted.

DES-SQL> insert into u values(2,2)
Info: 1 tuple inserted.

DES-SQL> insert into t values(1,2,3,4)
Info: 1 tuple inserted.

DES-SQL> /listing
s(2,4).
t(1,2,3,4).
u(2,2).

4.2.4.2 Creating Vie3s

CREATE [OR REPLACE] VIEW ViewName(Column1, ..., ColumnN)


Fernando Senz-Prez 75/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

AS SQLStatement
This slalenenl defines lhe viev schena in a siniIai vay as defining lalIes. If
lhe oplionaI cIause OR REPLACE is used, lhe viev is diopped if exisled aIieady. Olhei
lupIes oi iuIes asseiled (vilh lhe connand /assert) aie nol deIeled. The viev is
ciealed vilh lhe SQL slalenenl SQLStatement as ils definilion.
Nole lhal coIunn nanes aie nandaloiy.
LxanpIes:

DES> /dbschema
Info: Table(s):
* s(a:number(integer),b:number(integer))
- PK: [a,b]
* u(b:number(integer),c:number(integer))
- PK: [b]
*
t(a:number(integer),b:number(integer),c:number(integer),d:number
(integer))
- PK: [a,c]
- FK: t.[b,d] -> s.[a,b]
- FK: t.[b] -> u.[b]
Info: View(s):
* v(a:number(integer),b:number(integer),c:number(integer),
d:number(integer))
- Defining SQL Statement:
SELECT ALL *
FROM
t
WHERE a > 1;
- Datalog equivalent rules:
v(A,B,C,D) :-
t(A,B,C,D),
A > 1.
* w(a:number(integer),b:number(integer))
- Defining SQL Statement:
SELECT ALL t.a, s.b
FROM
t,
s
WHERE t.a > s.a;
- Datalog equivalent rules:
w(A,B) :-
t(A,C,D,E),
s(F,B),
A > F.
Info: No integrity constraints.
Nole lhal piinaiy key consliainls foIIov lhe lalIe schena, and infeiied lypes
aie in lhe viev schena.
4.2.4.3 Dro&&ing Aa*les

DROP TABLE [IF EXISTS] TableName,...,TableName


Fernando Senz-Prez 76/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

This slalenenl diops lhe lalIe schena coiiesponding lo each one of lhe
piovided nanes (TableName), deIeling aII of ils lupIes (vhelhei lhey veie inseiled
vilh INSERT oi vilh lhe connand /assert) and iuIes (vhich nighl have leen
added via /assert). If lhe oplionaI cIause IF EXISTS is incIuded, diopping an
inexislenl lalIe does nol iaise an eiioi.
LxanpIe:

DROP TABLE t;

4.2.4.4 Dro&&ing Vie3s

DROP VIEW ViewName
This slalenenl diops lhe viev vilh nane ViewName, deIeling aII of ils lupIes
(vhelhei lhey veie inseiled vilh INSLRT oi vilh lhe connand /assert) and iuIes
(vhich nighl have leen added via /assert). Olhei lupIes oi iuIes asseiled (vilh lhe
connand /assert) aie nol deIeled.
LxanpIe:

DROP VIEW v;
4.2.4.% +enaming Aa*les

RENAME TABLE TableName TO NewTableName
This non slandaid slalenenl (foIIoving IM D2) aIIovs lo change lhe nane of
lalIe TableName lo NewTableName. Ioieign keys iefeiiing lo lhis lalIe aie nodified
accoidingIy. AIso, vievs incIuding iefeienes lo lhis lalIe aie nodified lo iefei lo lhe
nev nane.
4.2.4." +enaming Vie3s

RENAME VIEW ViewName TO NewViewName
This non slandaid slalenenl (foIIoving IM D2) aIIovs lo change lhe nane of
viev ViewName lo NewViewName. AIso, vievs incIuding iefeiences lo lhis viev aie
nodified lo iefei lo lhe nev nane.
4.2.4.( Dro&&ing Data*ases

DROP DATABASE
This slalenenl diops lhe cuiienl dalalase, diopping aII lalIes, vievs, and iuIes
(lhis incIudes DalaIog iuIes and consliainls lhal nay have leen asseiled oi consuIled).
Il lehaves exaclIy as lhe connand /abolish.
LxanpIe:

DROP DATABASE;
4.2.% Data Mani&ulation $anguage
This pail of lhe Ianguage deaIs vilh inseiling and deIeling lupIes fion lalIes.
Theie is no piovision foi updaling lupIes.


Fernando Senz-Prez 77/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.2.%.1 Inserting Au&les

INSERT INTO TableName[(Col1,,ColN)] VALUES (Cte1,...,CteN) [,
..., (Cte1,...,CteN)]
This slalenenl inseils inlo lhe lalIe TableName as nany lupIes as lhose luiIl
vilh each lupIe of vaIues Cte1, ..., CteN. Col1 lo ColN aie non-iepealed coIunn
nanes of lhe lalIe. If no coIunn nanes aie given, N is expecled lo le lhe nunlei of
coIunns of lhe lalIe. If coIunn nanes aie given, each vaIue Ctei coiiesponds lo
coIunn nane Coli. Ioi lhose coIunn nanes vhich aie nol piovided in a coIunn
nane sequence, nuIIs aie inseiled.
The nexl exanpIe inseils a singIe lupIe:

CREATE TABLE t(a int, b int)
INSERT INTO t VALUES (1,1)
The nexl one inseils a singIe lupIe inlo lhe sane lalIe vilh a nuII foi coIunn a:

INSERT INTO t(b) VALUES (2)
Which is equivaIenl lo:

INSERT INTO t(b,a) VALUES (2,null)
and iepiesenls lhe lupIe (null,2). (Nole lhal lhe oidei of piovided coIunn nanes
aie ieveised vilh iespecl lo lhe lalIe definilion.)
Ioi inseiling seveiaI lupIes al a line:

INSERT INTO t VALUES (1,1),(null,2)
Anolhei foin of lhe INSERT slalenenl aIIovs lo inseiling lupIes vhich aie lhe
iesuIl sel fion a SELECT slalenenl:

INSERT INTO TableName[(Col1,,ColN)] SQLStatement
This slalenenl inseils inlo lhe lalIe TableName as nany lupIes as ieluined ly
lhe SQL slalenenl SQLStatement. This slalenenl has lo ieluin as nany coIunns as
eilhei lhe coIunns of TableName, if no coIunn nanes aie given, oi lhe nunlei of
piovided coIunn nanes (N), olheivise.
LxanpIes:

INSERT INTO t SELECT * FROM s
You can aIso inseil lupIes inlo a lalIe coning diieclIy (oi indiieclIy) fion lhe
lalIe ilseIf foi dupIicaling iovs, as in:

INSERT INTO t SELECT * FROM t
Nole lhal lheie is no iecuision in lhis queiy as lhe souice lalIe t is nol changed
duiing soIving lhe SELECT slalenenl.
Ioi lesling lhe nev (dupIicaled) conlenls of t, you have lo use /listing t,
inslead of a SELECT, since lhis slalenenl aIvays ieluins a sel (no dupIicales) vhen
dupIicales aie disalIed (cf. Seclion 4.1.9).


Fernando Senz-Prez 78/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

You can specify coIunns of lhe laigel lalIe as in:

INSERT INTO t(b) SELECT a FROM t
vhich inseils as nany iovs in l as il had lefoie inseilion, and foi each iov, a
nev lupIe is luiIl vilh lhe vaIue of lhe souice coIunn a in lhe laigel coIunn b, and
nuII in lhe laigel coIunn a.
4.2.%.2 Deleting Au&les

DELETE FROM TableName
This slalenenl deIeles aII lhe lupIes of lhe lalIe TableName. Il does nol deIele
pioduclion iuIes asseiled via /assert.
LxanpIe:

DELETE FROM t
Anolhei foin of lhe DELETE slalenenl aIIovs lo deIeling lupIes vhich fuIfiI a
given condilion:

DELETE FROM TableName WHERE Condition
This slalenenl deIeles fion lhe lalIe TableName aII of ils lupIes nalching lhe
condilion Condition. Il does nol deIele pioduclion iuIes asseiled via /assert.
LxanpIe:

DELETE FROM t WHERE a NOT IN (SELECT a FROM s)
4.2." Data #uery $anguage
Theie aie lhiee nain lypes of SQL queiy slalenenls: SELECT slalenenls, sel
slalenenls (UNION, INTERSECT, and EXCEPT), and WITH slalenenls (foi luiIding
iecuisive queiies).
4.2.".1 4asic S#$ #ueries
The synlax of lhe lasic SQL queiy slalenenl is:

SELECT [DISTINCT|ALL] ProjectionList
[FROM Relations
[WHERE Condition]
[ORDER BY OrdExpressions] ]
Wheie:
Squaie liackels indicale lhal lhe encIosed lexl is oplionaI. AIso, lhe veilicaI lai is
used lo denole aIleinalives.
ProjectionList is a Iisl of conna-sepaialed coIunns oi aiilhnelic expiessions
lhal viII le ieluined as a lupIe iesuIl. WiIdcaids aie aIIoved, as * (foi iefeiiing lo
aII lhe coIunns in lhe dala souice) and Relation.* (foi iefeiiing lo aII lhe
coIunns in lhe ieIalion Relation). The nane Relation can le lhe nane of a
lalIe oi an aIias (foi a lalIe oi sulqueiy). CIause DISTINCT discaids dupIicales
vheieas cIause ALL does nol (lhis is onIy nolicealIe vhen dupIicales aie enalIed
vilh lhe connand /duplicates on).


Fernando Senz-Prez 7/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Condition is a IogicaI condilion luiIl fion conpaiison opeialois (=, <>, <, >, >=,
and <=), ooIean opeialois (AND, OR, and NOT), ooIean conslanls (TRUE, FALSE),
lhe exislence opeialoi (EXISTS) and lhe incIusion opeialoi (IN). See lhe giannai
desciiplion in Seclion 4.2.8 foi delaiIs. Sulqueiies aie aIIoved vilh no Iinilalions.
Relations is a Iisl of conna-sepaialed ieIalion definilions. A ieIalion can le
eilhei a lalIe nane, oi a viev nane, oi a sulqueiy, oi a join ieIalion. They can le
ienaned via aIiases. If no FROM cIause is piovided, lhe luiIl-in DUAL ieIalion is
used as a dala souice (cf. Seclion 4.2.6.1.2).
OrdExpressions is a Iisl of conna-sepaialed oideiing expiessions. An oideiing
expiession can le eilhei sinpIy an expiession oi an expiession foIIoved ly lhe
oideiing ciileiiun (ASC -oi ASCENDING- foi ascending, and DESC -oi
DESCENDING- foi descending). Ansveis aie oideied ly defauIl (see
/order_answer) lul lhis oidei is oveiiided if lhe ORDER BY cIause is eilhei
diieclIy used in a queiy oi in lhe definilion of a viev lhe queiy iefeis lo.
LxanpIes:
Civen lhe lalIes:

CREATE TABLE s(a int, b int);
CREATE TABLE t(a int, b int);
CREATE TABLE v(a int, b int);
We can sulnil lhe foIIoving queiies:

SELECT distinct a
FROM t

SELECT t.*, s.b
FROM t,s,v
WHERE t.a=s.a AND v.b=t.b

SELECT t.a, s.b, t.a+s.b
FROM t,s
WHERE t.a=s.a

SELECT *
FROM (SELECT * from t) as r1,
(SELECT * from s) as r2
WHERE r1.a=r2.b;

SELECT *
FROM s
WHERE s.a NOT IN SELECT a FROM t;

SELECT *
FROM s
WHERE EXISTS
SELECT a
FROM t
WHERE t.a=s.a;

SELECT *


Fernando Senz-Prez 8!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

FROM s
WHERE s.a > (SELECT a FROM t);

SELECT 1, a1+a2, a+1 AS a1, a+2 AS a2
FROM t;

SELECT 1;
Noles:
SQL aiilhnelic expiessions foIIov lhe sane synlax as DalaIog.
An SQL aiilhnelic expiession can le ienaned and used in olhei expiessions.
CiicuIai definilions viII yieId exceplions al iun-line, as in a+a3 AS a3
A join ieIalion is eilhei of lhe foin:

Relation NATURAL JoinOp Relation
oi:

Relation JoinOp Relation [JoinCondition]
Wheie Relation is as lefoie (vilhoul any Iinilalion), }oinOI is any join
opeialoi (incIuding INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, and
FULL OUTER JOIN), and JoinCondition can le eilhei:

ON Condition
oi:

USING (Column1,...,ColumnN)
Wheie Condition is as desciiled in a WHERE cIause, and Column1, ...,
ColumnN aie connon coIunn nanes of lhe joined ieIalions.
LxanpIes:

Civen lhe lalIes:

CREATE TABLE s(a int, b int);
CREATE TABLE t(a int, b int);
CREATE TABLE v(a int, b int);
We can sulnil lhe foIIoving queiies:

SELECT *
FROM t INNER JOIN s ON t.a=s.a AND t.b=s.b;

SELECT *
FROM t NATURAL INNER JOIN s;

SELECT *
FROM t INNER JOIN s USING (a,b);

SELECT * FROM t INNER JOIN s USING (a);



Fernando Senz-Prez 81/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

SELECT *
FROM t INNER JOIN s USING (b);

SELECT *
FROM (t INNER JOIN s ON t.a=s.a) AS s, v
WHERE s.a=v.a;

SELECT *
FROM (t LEFT JOIN s ON t.a=s.a) RIGHT JOIN v ON t.a=v.a;

SELECT * FROM t FULL JOIN s ON t.a=s.a;

1oteH
The defauIl keyvoid ALL foIIoving SELECT ielains dupIicales vhenevei
dupIicales aie enalIed (connand /dupIicales on). In luin, DISTINCT discaids
dupIicales. ul nole lhal if dupIicales aie disalIed, lolh ALL and DISTINCT lehave
lhe sane (i.e., discaiding dupIicales).
4.2.".1.1 Ao&G1 #ueries
The nunlei of conpuled lupIes foi a seIecl slalenenl can le Iiniled vilh lhe
so-caIIed Top-N queiies. ISO 2OO8 incIudes lhis as a finaI cIause in lhe seIecl slalenenl:

SELECT [DISTINCT|ALL] ProjectionList
FROM Rels

FETCH FIRST Integer ROWS ONLY
Hovevei, DLS aIso piovides anolhei non-slandaid, lul connon foin in olhei
RDMS's of such queiies:

SELECT [TOP Integer] [DISTINCT|ALL] ProjectionList

You can svilch lhe oidei of lhe lop and dislincl cIauses, and even specify lolh
foins of Top-N queiies in lhe sane slalenenl, as Iong as lhey expiess lhe sane Iinil.
4.2.".1.2 A/e dual ta*le
The dual lalIe is a speciaI one-iov, one-coIunn lalIe piesenl ly defauIl in aII
OiacIe dalalase inslaIIalions. Il is suilalIe foi use in seIecling a pseudocoIunn vilh no
dala souice. As pioposilionaI ieIalions aie aIso aIIoved in DLS, dual does nol need a
coIunn al aII, and il is lheiefoie defined as a singIe facl vilhoul aigunenls. This lalIe
can le used lo conpule aiilhnelics as, e.g.:

DES-SQL> select 1+1 from dual
answer($a0) ->
{
answer(2)
}
Info: 1 tuple computed.
As in MySQL, DLS aIso aIIovs lo onil lhe FROM cIause in lheses cases (lhe
conpiIalion fion SQL lo DalaIog adds lhe dual lalIe as dala souice):



Fernando Senz-Prez 82/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES-SQL> select 1+1
answer($a0) ->
{
answer(2)
}
Info: 1 tuple computed.
AIlhough lhis lalIe is nol dispIayed vilh lhe connand /dbschema, il can le
neveilheIess diopped vilh a DROP TABLE SQL slalenenl. If il is deIeled, lhe jusl
desciiled lehavioui is no Iongei possilIe. In addilion, il cannol le iedecIaied vilh a
CREATE TABLE SQL slalenenl, lul vilh a lype decIaialion, as :-type(dual). olh
DROP DATABASE slalenenl and /abolish connand iesloie lhis lalIe.
4.2.".2 +elational Di0ision in S#$
The division opeialion vas oiiginaIIy inlioduced as a ieIalionaI opeialion in
Codd's papei aloul ieIalionaI nodeI. AIlhough il seens lo le a piaclicaI opeialion, il is
nol incIuded in cuiienl DMS's. Hovevei, DLS incIudes a DIVISION opeialoi lhal can
le used in lhe FROM cIause of a SELECT slalenenl. The nexl syslen session iIIusliales
ils use:

DES> create table t(a int, b int)
DES> create table s(a int)
DES> insert into t values (1,1)
Info: 1 tuple inserted.
DES> insert into t values (1,2)
Info: 1 tuple inserted.
DES> insert into t values (2,1)
Info: 1 tuple inserted.
DES> insert into s values (1)
Info: 1 tuple inserted.
DES> insert into s values (2)
Info: 1 tuple inserted.
DES> select * from t division s
answer(t.b:number(integer)) ->
{
answer(1)
}
Info: 1 tuple computed.
4.2.".3 Set S#$ #ueries
The lhiee sel opeialois defined in lhe slandaid aie avaiIalIe: UNION, EXCEPT,
and INTERSECT. (AIso, OiacIe's MINUS is aIIoved as a synonynous foi EXCEPT.) The
fiisl one aIso adnils lhe foin UNION ALL foi ielaining dupIicales. The synlax of a sel
SQL queiy is:

SQLStatement
SetOperator
SQLStatement
Wheie SQLStatement is any SQL slalenenl desciiled in lhe dala queiy pail
(vilhoul any Iinilalion). SetOperator is any of lhe alovenenlioned sel opeialois.
LxanpIes:



Fernando Senz-Prez 83/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

(SELECT * FROM s) UNION (SELECT * FROM t);

(SELECT * FROM s) UNION ALL (SELECT * FROM t);

(SELECT * FROM s) INTERSECT (SELECT * FROM t);

(SELECT * FROM s) EXCEPT (SELECT * FROM t);
Nole lhal paienlheses aie nol nandaloiy in lhese cases and aie onIy used foi
ieadaliIily.
4.2.".4 WITH S#$ #ueries
The WITH cIause, as inlioduced in lhe SQL:1999 slandaid and avaiIalIe in
seveiaI RDMS as D2, OiacIe and SQL Seivei, is inlended in pailicuIai lo define
iecuisive queiies. Ils synlax is:

WITH LocalViewDefinition1,
...,
LocalViewDefinitionN
SQLStatement
Wheie SQLStatement is any SQL slalenenl, and
LocalViewDefinition1, ..., LocalViewDefinition1 aie (IocaI) viev definilions
lhal can onIy le used inside SQLStatement. These IocaI vievs aie nol sloied in lhe
dalalase and aie ialhei conpuled vhen execuling SQLStatement. AIlhough lhey aie
IocaI, lhey nusl have diffeienl nanes fion exisling oljecls (lalIes oi vievs). The
synlax of a IocaI viev definilion is as foIIovs:

[RECURSIVE] ViewName(Column1, ..., ColumnN) AS SQLStatement
Heie, lhe keyvoid RECURSIVE foi defining iecuisive vievs is nol nandaloiy
(lhe paisei sinpIy ignoies il).
LxanpIes
6
:

CREATE TABLE flights(airline,frm,to,departs,arrives);

WITH
RECURSIVE reaches(frm,to) AS
(SELECT frm,to FROM flights)
UNION
(SELECT r1.frm,r2.to
FROM reaches AS r1, reaches AS r2
WHERE r1.to=r2.frm)
SELECT * FROM reaches;

WITH
Triples(airline,frm,to) AS
SELECT airline,frm,to
FROM flights,
RECURSIVE Reaches(airline,frm,to) AS

6
Adapled fion |CUWO2j.


Fernando Senz-Prez 84/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

(SELECT * FROM Triples)
UNION
(SELECT Triples.airline,Triples.frm,Reaches.to
FROM Triples,Reaches
WHERE Triples.to = Reaches.frm AND
Triples.airline=Reaches.airline)
(SELECT frm,to FROM Reaches WHERE airline = 'UA')
EXCEPT
(SELECT frm,to FROM Reaches WHERE airline = 'AA');

In addilion, shoilei definilions foi iecuisive vievs aie aIIoved in DLS. The nexl
viev deIiveis lhe sane iesuIl sel as lhe fiisl exanpIe alove:

CREATE VIEW reaches(frm,to) AS
(SELECT frm,to FROM flights)
UNION
(SELECT r1.frm,r2.to
FROM reaches AS r1, reaches AS r2
WHERE r1.to=r2.frm);

4.2.".% @y&ot/etical S#$ #ueries
A noveI addilion lo SQL in DLS incIudes hypolhelicaI queiies. Such queiies aie
usefuI, foi inslance, in decision suppoil syslens as lhey aIIov lo sulnil a queiy ly
assuning sone knovIedge vhich is nol in lhe dalalase.
Synlax of hypolhelicaI queiies is pioposed as:

ASSUME
LocalAssumption1,
...,
LocalAssumptionN
SQLStatement
Wheie SQLStatement is any SQL DQL slalenenl, and LocalAssumption1,
..., LocalAssumptionN aie of lhe foin:

DQLStatement IN ExistingRelation
And LocalAssumptionN aie added as unions lo exisling ieIalions (eilhei
lalIes oi vievs). Synlax of lhese IocaI viev definilions aie as in WITH slalenenls.
As an exanpIe, Iel's considei a fIighl dalalase defined ly lhe foIIoving:

CREATE TABLE flight(origin string, destination string, time
real);

INSERT INTO flight VALUES('lon','ny',9.0);
INSERT INTO flight VALUES('mad','par',1.5);
INSERT INTO flight VALUES('par','ny',10.0);

CREATE OR REPLACE VIEW travel(origin,destination,time) AS WITH
connected(origin,destination,time) AS
SELECT * FROM flight
UNION


Fernando Senz-Prez 85/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

SELECT flight.origin,connected.destination,
flight.time+connected.time
FROM flight,connected
WHERE flight.destination = connected.origin
SELECT * FROM connected;
Heie, ieIalion flight iepiesenls possilIe diiecl fIighls lelveen Iocalions, and
travel iepiesenls possilIe conneclions ly using one oi noie diiecl fIighls. olh
incIude fIighl line. y queiying lhe ieIalion liaveI, ve gel:

DES> select * from travel
answer(travel.origin:string(varchar),travel.destination:string(v
archar),travel.time:number(float)) ->
{
answer(lon,ny,9.0),
answer(mad,ny,11.5),
answer(mad,par,1.5),
answer(par,ny,10.0)
}
Info: 4 tuples computed.
Nov, if ve assune lheie is a lupIe flight('mad','lon',2.0), ve can
queiy lhe dalalase vilh lhis assunplion vilh lhe foIIoving queiy (vilh nuIli-Iine
inpul enalIed):

DES> ASSUME
SELECT 'mad','lon',2.0
IN
flight(origin,destination,time)
SELECT * FROM travel;

answer(travel.origin:string(varchar),travel.destination:string(v
archar),travel.time:number(float)) ->
{
answer(lon,ny,9.0),
answer(mad,lon,2.0),
answer(mad,ny,11.0),
answer(mad,ny,11.5),
answer(mad,par,1.5),
answer(par,ny,10.0)
}
Info: 6 tuples computed.
Nole lhal lhe SELECT slalenenl foIIoving lhe keyvoid ASSUME sinpIy slands
foi lhe consliuclion of a singIe lupIe foi lalIe flight (such slalenenl can le olheivise
slaled as SELECT 'mad','lon',2.0 FROM dual, vheie dual is lhe luiIl-in lalIe
desciiled in Seclion 4.2.6.1.2).
In addilion, nol onIy lupIes can le exlensionaIIy assuned, lul any SQL DQL
slalenenl, i.e., lupIes inlensionaIIy assuned. As an exanpIe, Iel's suppose lhal lhe
ieIalion flight is as pieviousIy defined, and a viev connect lhal dispIays Iocalions
connecled ly diiecl fIighls:

DES> CREATE VIEW connect(origin,destination) AS
SELECT origin,destination FROM flight;


Fernando Senz-Prez 86/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


DES> SELECT * FROM connect;
answer(connect.origin:string(varchar),connect.destination:string
(varchar)) ->
{
answer(lon,ny),
answer(mad,par),
answer(par,ny)
}
Info: 3 tuples computed.
Then, if ve assune lhal conneclions aie aIIoved vilh liansils, ve can sulnil
lhe foIIoving hypolhelicaI queiy (nole lhal lhe assuned SQL slalenenl is iecuisive):

DES> ASSUME
(SELECT flight.origin,connect.destination
FROM flight,connect
WHERE flight.destination = connect.origin)
IN
connect(origin,destination)
SELECT * FROM connect;

answer(connect.origin:string(varchar),connect.destination:string
(varchar)) ->
{
answer(lon,ny),
answer(mad,ny),
answer(mad,par),
answer(par,ny)
}
Info: 4 tuples computed.
In addilion lo lhis, one can use a WITH slalenenl inslead of an ASSUML
slalenenl, ly sinpIy slaling an exisling ieIalion in lhe definilion of lhe IocaI viev. Ioi
inslance, foi lhe Iasl exanpIe, ve can viile:

DES> WITH
connect(origin,destination) AS
(SELECT flight.origin,connect.destination
FROM flight,connect
WHERE flight.destination = connect.origin)
SELECT *
FROM connect;

answer(connect.origin:string(varchar),connect.destination:string
(varchar)) ->
{
answer(lon,ny),
answer(mad,ny),
answer(mad,par),
answer(par,ny)
}
Info: 4 tuples computed.


Fernando Senz-Prez 87/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

One can use seveiaI assunplions in lhe sane queiy, lul onIy one foi a given
ieIalion. If needed, you can assune seveiaI iuIes ly using UNION. Ioi exanpIe:

WITH
flight(origin,destination,time) AS
SELECT 'mad','lon',2.0
UNION
SELECT 'ny','par',10.0
SELECT *
FROM travel;
vhich is equivaIenl lo:

ASSUME
SELECT 'mad','lon',2.0
UNION
SELECT 'ny','par',10.0
IN
flight(origin,destination,time)
SELECT *
FROM travel;
1ote:
SQL queiies aie onIy aIIoved as such, i.e., lhey cannol le used as pail of any
viev decIaialion. Iuilhei veisions nighl aIIov lhis.
4.2.( In:ormation Sc/ema $anguage DIS$E
SeveiaI non-slandaid slalenenls aie piovided lo dispIay schena infoinalion:
SHOW TABLES; Lisl lalIe nanes. TAPI enabled
SHOW VIEWS; Lisl viev nanes. TAPI enabled
SHOW DATABASES; Lisl dalalase nanes. TAPI enabled
DESCRIBE Relation; DispIay schena foi ReIalion, as /dbschema
4.2.8 S#$ !rammar
Heie, leininaI synloIs aie: Iaienlheses, connas, senicoIons, singIe dols,
asleiisks, and aposliophes. Olhei leininaI synloIs aie conpIeleIy viillen in capilaIs,
as SELECT. Ieicenlage synloIs (%) slail connenls. Usei idenlifieis nusl slail vilh a
Iellei and consisl of Ielleis and nunleis, olheivise, a usei idenlifiei can le encIosed
lelveen quolalion naiks (lolh squaie liackels and doulIe quoles aie suppoiled) and
conlain any chaiacleis. Nexl, SQLstmt slands foi a vaIid SQL slalenenl.

SQLstmt ::=
DDLstmt[;]
|
DMLstmt[;]
|
DQLstmt[;]
|
ISLstmt[;]



Fernando Senz-Prez 88/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DDL (Data Definition Language) statements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

DDLstmt ::=
CREATE [OR REPLACE] TABLE CompleteConstrainedSchema
|
CREATE [OR REPLACE] TABLE TableName LIKE TableName
|
CREATE [OR REPLACE] VIEW ViewSchema AS DQLstmt
|
RENAME TABLE TableName TO TableName
|
RENAME VIEW ViewName TO ViewName
|
DROP TABLE [IF EXISTS] TableName,...,TableName % Extended
syntax following MySQL 5.6
|
DROP VIEW [IF EXISTS] ViewName
|
DROP DATABASE

Schema ::=
RelationName
|
RelationName(Att,...,Att)

CompleteConstrainedSchema ::=
RelationName(Att Type [ColumnConstraint ...
ColumnConstraint],...,Att Type [ColumnConstraint ...
ColumnConstraint] [, TableConstraints])

CompleteSchema ::=
RelationName(Att Type,...,Att Type)

Type ::=
CHAR(n) % fixed-length string of n characters
|
% CHARACTER(n) % equivalent to the former
% |
CHAR % fixed-length string of 1 character
|
VARCHAR(n) % variable-length string of up to n characters
|
VARCHAR2(n) % Oracle's variable-length string of up to n
characters
|
VARCHAR % variable-length string of up to the maximum length
of the underlying Prolog atom
|
STRING % As VARCHAR
|
% CHARACTER VARYING(n) % equivalent to the former
% |


Fernando Senz-Prez 8/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

INT
|
INTEGER % equivalent to the former
|
% SMALLINT
% |
% NUMERIC(p,d) % a total of p digits, where d of those are in
the decimal place
% |
REAL
|
% DOUBLE PRECISION % equivalent to the former
% |
% FLOAT(n) % with precision of at least n digits
% |
% DATE % four digit year, month and day
% |
% TIME % hours, minutes and seconds
% |
% TIMESTAMP % combination of date and time


ColumnConstraint ::=
NOT NULL
|
PRIMARY KEY
|
UNIQUE
|
CANDIDATE KEY
|
REFERENCES TableName[(Att)]
|
CHECK (CheckConstraint)

TableConstraints ::=
TableConstraint,...,TableConstraint

TableConstraint ::=
UNIQUE (Att,...,Att)
|
CANDIDATE KEY (Att,...,Att)
|
PRIMARY KEY (Att,...,Att)
|
FOREIGN KEY (Att,...,Att) REFERENCES TableName[(Att,...,Att)]
|
CHECK (CheckConstraint)

CheckConstraint ::=
WhereCondition
|
(Att,...,Att) DETERMINED BY (Att,...,Att)



Fernando Senz-Prez !/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

RelationName is a user identifier for naming tables, views and
aliases
TableName is a user identifier for naming tables
ViewName is a user identifier for naming views
Att is a user identifier for naming relation attributes

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DML (Data Manipulation Language) statements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

DMLstmt ::=
INSERT INTO TableName[(Att,...,Att)]
VALUES (Cte,...,Cte) [, ..., (Cte,...,Cte)]
|
INSERT INTO TableName[(Att,...,Att)] DQLstmt
|
DELETE FROM TableName
|
DELETE FROM TableName WHERE Condition
|
UPDATE TableName SET Att1=Expr1,...,Attn=Exprn WHERE Condition

Cte is a constant

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DQL (Data Query Language) statements:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

DQLstmt ::=
(DQLstmt)
|
UBSQL

UBSQL ::=
SELECTstmt
|
DQLstmt UNION [ALL] DQLstmt
|
DQLstmt EXCEPT DQLstmt
|
DQLstmt MINUS DQLstmt
|
DQLstmt INTERSECT DQLstmt
|
WITH LocalViewDefinition,...,LocalViewDefinition DQLstmt
|
ASSUME LocalAssumption,...,LocalAssumption DQLstmt

LocalViewDefinition ::=
[RECURSIVE] CompleteSchema AS DQLstmt

LocalAssumption ::=
DQLstmt IN CompleteSchema



Fernando Senz-Prez 1/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

SELECTstmt ::=
SELECT [TOP Integer] [[ALL|DISTINCT]] SelectExpressionList
[FROM Rels
[WHERE WhereCondition]
[GROUP BY Atts]
[HAVING HavingCondition]
[ORDER BY OrderDescription]
[FETCH FIRST Integer ROWS ONLY]]

Atts ::=
Att,...,Att

OrderDescription ::=
Att [[ASC|DESC]],...,Att [[ASC|DESC]]

SelectExpressionList ::=
*
|
SelectExpression,...,SelectExpression

SelectExpression ::=
UnrenamedSelectExpression
|
RenamedExpression

UnrenamedSelectExpression ::=
Att
|
RelationName.Att
|
RelationName.*
|
ArithmeticExpression
|
DQLstmt

RenamedExpression ::=
UnrenamedExpression [AS] Identifier

ArithmeticExpression ::=
Op1 ArithmeticExpression
|
ArithmeticExpression Op2 ArithmeticExpression
|
ArithmeticFunction(ArithmeticExpression,...,
ArithmeticExpression)
|
Number
|
Att
|
RelationName.Att
|
ArithmeticConstant


Fernando Senz-Prez 2/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

|
DQLstmt

Op1 ::=
- | \

Op2 ::=
^ | ** | * | / | // | rem | \/ | xor | + | - | /\ | << | >>

ArithmeticFunction ::=
sqrt/1 | ln/1 | log/1 | log/2 | sin/1 | cos/1 | tan/1 |
cot/1
| asin/1 | acos/1 | atan/1 | acot/1 | abs/1 | float/1
| integer/1 | sign/1 | gcd/2 | min/2 | max/2 | truncate/1
| float_integer_part/1 | float_fractional_part/1
| round/1 | floor/1 | ceiling/1

Aggregate Functions:
The argument may include a prefix "distinct" for all but "min"
and "max":
avg/1 | count/1 | count/0 | max/1 | min/1 | sum/1 | times/1

ArithmeticConstant ::=
pi | e

Rels ::=
Rel,...,Rel

Rel ::=
UnrenamedRel
|
RenamedRel

UnrenamedRel ::=
TableName
|
ViewName
|
DQLstmt
|
JoinRel
|
DivRel

RenamedRel ::=
UnrenamedRel [AS] Identifier

JoinRel ::=
Rel [NATURAL] JoinOp Rel [JoinCondition]

JoinOp ::=
INNER JOIN
|
LEFT [OUTER] JOIN


Fernando Senz-Prez 3/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

|
RIGHT [OUTER] JOIN
|
FULL [OUTER] JOIN

JoinCondition ::=
ON WhereCondition
|
USING (Atts)

DivRel ::=
Rel DIVISION Rel

WhereCondition ::=
BWhereCondition
|
UBWhereCondition

HavingCondition
As WhereCondition, but including aggregate functions

BWhereCondition ::=
(WhereCondition)

UBWhereCondition ::=
TRUE
|
FALSE
|
EXISTS DQLstmt
|
NOT (WhereCondition)
|
(AttOrCte,...,AttOrCte) [NOT] IN DQLstmt
|
WhereExpression IS [NOT] NULL
|
WhereExpression [NOT] IN DQLstmt
|
WhereExpression Operator [[ALL|ANY]] WhereExpression
|
WhereCondition [AND|OR] WhereCondition

WhereExpression ::=
Att
|
Cte
|
ArithmeticExpression
|
DQLstmt

AggrArithmeticExpression ::=
[AVG|MIN|MAX|SUM]([DISTINCT] Att)


Fernando Senz-Prez 4/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

|
COUNT([*|[DISTINCT] Att])

AttOrCte ::=
Att
|
Cte

Operator ::=
= | <> | < | > | >= | <=

Cte ::=
Number
|
'String'
|
NULL

Number is an inlegei oi fIoaling-poinl nunlei

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ISL (Information Schema Language) statements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ISLstmt ::=
SHOW TABLES
|
SHOW VIEWS
|
SHOW DATABASES
|
DESCRIBE [TableName|ViewName]

4.3 DE)tendedE +elational 2lge*ra
IoIIoving lhe seninaI pioposaI |Codd7Oj lheie have leen sone exlensions lo
lhe lasic and addilionaI opeialois in lhe oiiginaI pioposaI. Heie, ve incIude aII lhe
oiiginaI and exlended opeialois foi deaIing vilh oulei joins, dupIicale eIininalion,
iecuision, and giouping vilh aggiegales.
Wilh iespecl lo lexluaI synlax, ve foIIov |DielO1j, vheie aigunenls of
funclions aie encIosed lelveen paienlheses (as ieIalions), and sulsciipls and
supeisciipls aie deIiniled lelveen lIanks. Aigunenls in infix opeialois aie nol
encIosed lelveen any deIinileis, aIso paienlheses can le used lo enhance ieading.
Condilions and expiessions aie luiIl vilh lhe sane synlax as in SQL. LxanpIes leIov
iefei lo lhe dalalase defined in examples/relop.ra.
4.3.1 =&erators
This seclion incIudes desciiplions foi lasic, addilionaI and exlended opeialois.
4.3.1.1 4asic o&erators
SeIeclion

(R). SeIecl lupIes in ieIalion R nalching condilion .




Fernando Senz-Prez 5/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Conciele synlax:

select Condition (Relation)
LxanpIe:

select a<>'a1' (c);
Iiojeclion A1!"""!An(R). Reluin aII lupIes in R onIy vilh coIunns A1!"""!An.
Conciele synlax:

project A1,...,An (Relation)
LxanpIe:

project b (c);
Sel union R1 R2.
Conciele synlax:

Relation1 union Relation2
LxanpIe:

a union b;
Sel diffeience R1 - R2.
Conciele synlax:

Relation1 difference Relation2
LxanpIe:

a difference b;
Cailesian pioducl R1 R2.
Conciele synlax:

Relation1 product Relation2
LxanpIe:

a product b;
Renaning R2(A1,...,An)(R1). Renane R1 lo R2, and aIso aigunenls of R1 lo A1,...,An.
Conciele synlax:

rename Schema (Relation)
LxanpIe:

project v.a (rename v(a) (select true (a)));
Assignnenl R1(A1,...,An) R2. Cieale a nev ieIalion R1 vilh aigunenl nanes
A1,...,An as a copy of R2. Il aIIovs lo define nev vievs.
Conciele synlax:


Fernando Senz-Prez 6/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


Relation1 := Relation2
LxanpIe:

v(c) := select true (a);
4.3.1.2 2dditional o&erators
These opeialois can le expiessed in leins of lasic opeialois, and incIude:
Sel inleiseclion R1 R2.
Conciele synlax:

Relation1 intersect Relation2
LxanpIe:

a intersect b;
Thela join R1
R2. LquivaIenl lo

(R1 R2).
Conciele synlax:

Relation1 zjoin Condition Relation2
LxanpIe:

a zjoin a.a<b.b b;
NaluiaI (innei) join R1 R2. Reluin lupIes of R1 joined vilh R2 such lhal connon
alliilules aie paii vise equaI and occui onIy once in oulpul ieIalion.
Conciele synlax:

Relation1 njoin Relation2
LxanpIe:

a njoin c;
Division R1 R2. Reluin iesliiclions of lupIes in R1 lo lhe alliilule nanes of R1
vhich aie nol in lhe schena of R2, foi vhich il hoIds lhal aII lheii conlinalions
vilh lupIes in R2 aie piesenl in R1. The alliilules in R2 foin a piopei sulsel of
alliilules in R1.
Conciele synlax:

Relation1 division Relation2
LxanpIe:

a division c;
4.3.1.3 E)tended o&erators
These opeialois can not le expiessed in leins of foinei opeialois, and incIude:
Lxlended piojeclion (expiessions and ienanings) #1 A1!"""!#n An(R). Reluin lupIes of R
vilh a nev schena R(A1!"""!An) vilh coIunns #1!"""!#n vheie each #i is an expiession


Fernando Senz-Prez 7/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

luiIl fion conslanls, alliilules of R, and luiIl-in opeialois. If a given Ai is nol
piovided, lhe nane foi lhe coIunn is eilhei lhe coIunn #i, if il is a coIunn, oi il is
given an aililiaiy nev nane.
Conciele synlax:

project E1 A1,...,En An (Relation)
LxanpIes:

:-type(d(a:string,b:int)).
project b+1 (d);
project incb (project b+1 incb (d))
DupIicale eIininalion (R). Reluin lupIes in R, discaiding dupIicales.
Conciele synlax:

distinct (Relation)
LxanpIe:

distinct (project a (c));
Nole: As distinct is aIso a DalaIog (nela)piedicale, lhe queiy distinct (c)
fion lhe DalaIog pionpl vouId le soIved as a DalaIog queiy, inslead of a RA one.
Then, if you have lo ensuie youi queiy viII le evaIualed ly lhe RA piocessoi, you
can eilhei svilch lo RA vilh /ra, oi piepend lhe queiy vilh /ra, as foIIovs:

DES> % Either switch to RA:
DES>/ra
DES-RA> distinct (project a (c));
DES> /datalog
DES> % Or simply add /ra
DES>/ra distinct (project a (c));
Lefl oulei join R1

R2. IncIudes aII lupIes of R1 joined vilh nalching lupIes of R2


v.i.l. condilion . Those lupIes of R1 vhich do nol have nalching lupIes of R2 aie
aIso incIuded in lhe iesuIl, and coIunns coiiesponding lo R2 aie fiIIed vilh nuII
vaIues.
Conciele synlax:

Relation1 ljoin Condition Relation2
LxanpIe:

a ljoin a=b b;

Righl oulei join R1

R2. LquivaIenl lo R2

R1. R1

R2
Conciele synlax:

Relation1 rjoin Condition Relation2
LxanpIe:



Fernando Senz-Prez 8/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

a rjoin a=b b;
IuII oulei join R1

R2. LquivaIenl lo R1

R2 R1

R2.
Conciele synlax:

Relation1 fjoin Condition Relation2
LxanpIe:

a fjoin a=b b;
Ciouping vilh aggiegalions $1!"""!$n
#1!"""!#n

(R). uiId gioups of lupIes in R so lhal:


fiisl, each lupIe in lhe gioup have lhe sane vaIues foi alliilules $1!"""!$n , second,
nalches condilion (possilIy incIuding aggiegale funclions) and, lhiid, is
piojecled ly expiessions #1!"""!#n (aIso possilIy incIuding aggiegale funclions). An
enply Iisl of giouping alliilules $1!"""!$n is denoled ly an opening and a cIosing
liackel ([]).
Conciele synlax:

group_by GroupingAtts ProjectingExprs HavingCond (Relation)
LxanpIes:

% Number of employees
group_by [] count(*) true (employee);
% Employees with a salary greater than average salary,
% grouped by department
group_by dept id salary > avg(salary) (employee);
4.3.2 +ecursion in +2
Recuision in RA expiessions can le specified ly sinpIy incIuding lhe nane of
lhe viev vhich is leing defined in ils definilion lody. SoIving iecuision in RA has
leen pioposed as lhe appIicalion of a fixpoinl opeialoi lo an RA expiession (see, foi
inslance, |Agia88, HA92j). DLS conpiIes RA expiessions lo DalaIog piogians and
uses lhe (fixpoinl-lased) deduclive engine lo soIve lhen.
As an exanpIe of iecuision in RA, Iel's considei lhe foIIoving cIassic piogian
foi finding palhs in a giaph:

create table edge(origin string, destination string);

paths(origin, destination) :=
select true (edge)
union
project paths.origin, edge.destination
(select paths.destination=edge.origin (edge product paths));

select true (paths);
4.3.3 +2 !rammar
Heie, leininaI synloIs aie: Iaienlheses, connas, senicoIons, singIe dols,
asleiisks, and aposliophes. Olhei leininaI synloIs aie conpIeleIy viillen in capilaIs,


Fernando Senz-Prez /234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

as SELECT. Hovevei, lhey aie iecognized ly lhe paisei in any Iellei case. Ieicenlage
synloIs (%) slail connenls. Usei idenlifieis nusl slail vilh a Iellei and consisl of
Ielleis and nunleis, olheivise, a usei idenlifiei can le encIosed lelveen quolalion
naiks (lolh squaie liackels and doulIe quoles aie suppoiled) and conlain any
chaiacleis. Nexl, RAstmt slands foi a vaIid RA slalenenl.
This giannai is luiIl foIIoving |DielO1j, so lhal RA fiIes iead in WinRDI (a
looI desciiled in lhal look) aie aIso iead in DLS. DLS giannai exlends WinRDI
giannai in pioviding suppoil aIso foi: Thela join opeialoi, oulei join opeialois,
dupIicale eIininalion (dislincl opeialoi), giouping (group_by opeialoi), iecuisive
queiies, and ienaning opeialoi (lhis avoids lo iesoil lo luiIding nev ieIalions vilh lhe
assignnenl opeialoi :=, aIlhough il is suppoiled, loo).

RAstmt ::=
SELECT WhereCondition (RArel) % Selection (sigma)
|
PROJECT SelectExpressionList (RArel) % Projection (pi)
|
RENAME Schema (RArel) % Renaming (rho)
|
DISTINCT (RArel) % Duplicate elimination
|
RArel PRODUCT RArel % Cartesian Product
|
RArel DIVISION RArel % Division
|
RArel UNION RArel % Set union
|
RArel DIFFERENCE RArel % Set difference
|
RArel INTERSECT RArel % Set intersection
|
RArel NJOIN RArel % Natural join
|
RArel ZJOIN WhereCondition RArel % Zeta join
|
RArel LJOIN WhereCondition RArel % Left outer join
|
RArel RJOIN WhereCondition RArel % Right outer join
|
RArel FJOIN WhereCondition RArel % Full outer join
|
GROUP_BY GAtts SelectExpressionList HavingCondition (RArel)
% Grouping


RArel ::=
RAstmt
|
Relation

View definition (assignment statement):
RAview ::=
Schema := [RAstmt | Relation]


Fernando Senz-Prez 1!!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


Schema ::=
ViewName
|
ViewName(ColName,...,ColName)

GAtts :=
[]
|
Atts

Wheie Atts, Condition, SelectExpressionList and HavingCondition
aie as in SQL giannai.
4.4 ?rolog
Synlax of IioIog piogians and goaIs is lhe sane as foi DalaIog, incIuding aII
luiIl-in opeialois (cf. nexl Seclion) lul aggiegales. Nolice lhal negalion is viillen as
not(Goal), inslead of lhe usuaI \+ Goal.
When a goaI is soIved, inslead of dispIaying lhe vaiialIe sulslilulion foi lhe
ansvei, lhe goaI is dispIayed vilh lhe sulslilulion appIied, as in:

DES-Prolog> t(X)
t(1)
? (type ; for more solutions, <Intro> to continue) ;
t(2)
? (type ; for more solutions, <Intro> to continue) ;
no
4.% 4uiltGins
Mosl luiIl-ins aie shaied ly lhe foui Ianguages. Ioi inslance, v.i.l. conpaiison
opeialois, lhe onIy diffeience is lhe Iess oi equaI (=<) opeialoi used in DalaIog and
IioIog. This opeialoi is diffeienl fion lhe used in SQL and RA, vhich is viillen as <=.
The foinei is viillen lhal vay since in IioIog and DalaIog, il is dislinguished fion lhe
inpIicalion lo lhe Iefl opeialoi (<=). SQL does nol piovide inpIicalions, so, lhe SQL
synlax seens lo le noie appeaIing since lhe oidei of lhe lvo synloIs nalches lhe
oidei of voids.
Aiilhnelic expiessions aie consliucled vilh lhe sane luiIl-ins in lhe lhiee
Ianguages. Hovevei, in DalaIog and IioIog, you need lo use lhe infix is (cf. Seclion
4.5.2).
The luiIl-in piedicales is_null/1 and is_not_null/1 leIong lo lhe DalaIog
Ianguage.
AIso, consuIl Seclion 5.3 foi Iinilalions iegaiding safely in lhe use of luiIl-ins in
DalaIog.


Fernando Senz-Prez 1!1/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.%.1 Com&arison =&erators
AII conpaiison opeialois aie infix and appIy lo leins. Ioi lhe inequaIily and
disequaIily opeialois (giealei lhan, Iess lhan, elc.), nunleis aie conpaied in leins of
lheii aiilhnelicaI vaIue, olhei leins aie conpaied in IioIog slandaid oidei.
If a conpound lein is invoIved in a conpaiison opeialoi, il is evaIualed as an
aiilhnelic expiession and ils iesuIl is lhen conpaied (foi aII opeialois ly equaIily) oi
unified (foi equaIily).
AII conpaiison opeialois, lul equaIily, denand giound aigunenls since lhey
aie nol consliainls, lul lesl opeialois, and aigunenl donains aie infinile. If a giound
aigunenl is denanded and a vaiialIe is ieceived, an exceplion is iaised.
Nexl, ve Iisl lhe avaiIalIe conpaiison opeialois, vheie X and Y aie leins
(vaiialIes, conslanls oi aiilhnelic expiessions).
X = Y (Synlaclic equaIily)
Tesls synlaclic equaIily lelveen X and Y. Il aIso peifoins unificalion vhen
vaiialIes aie invoIved. This is lhe onIy conpaiison opeialoi lhal does nol denand
giound aigunenls.
X \= Y (Synlaclic disequaIily)
Tesls synlaclic disequaIily lelveen X and Y.
X > Y (Ciealei lhan)
Tesls vhelhei X is giealei lhan Y.
X >= Y (Ciealei lhan oi equaI lo)
Tesls vhelhei X is giealei lhan oi equaI lo lhan Y.
X < Y (Less lhan)
Tesls vhelhei X is Iess lhan Y.
X =< Y (Less lhan oi equaI lo)
Tesls vhelhei X is Iess lhan oi equaI lo Y.
4.%.2 Datalog and ?rolog 2rit/metic
oiioved fion nosl IioIog inpIenenlalions, aiilhnelic is aIIoved ly using
lhe infix opeialoi is, vhich is used lo consliucl a queiy vilh lvo aigunenls, as
foIIovs:

X is Expression
vheie X is a vaiialIe oi a nunlei, and Expression is an aiilhnelic expiession
luiIl fion nunleis, vaiialIes, luiIl-in aiilhnelic opeialois, conslanls and funclions,
nainIy foIIoving ISO foi IioIog (lhey aie IaleIIed, if so, in lhe Iislings leIov).
AvaiIaliIily of aiilhnelic luiIl-ins nainIy depend on lhe undeiIying IioIog syslen
(linaiy disliilulions cope vilh aII lhe Iisled luiIl-ins).
Al evaIualion line, lhe expiession nusl le giound (i.e., ils vaiialIes nusl le
lound lo nunleis oi conslanls), olheivise, piolIens as slaled in lhe pievious seclion
nay aiise. LvaIualing lhe alove queiy anounls lo evaIuale lhe aiilhnelic expiession
accoiding lo lhe usuaI aiilhnelic iuIes, vhich yieIds a nunlei (inlegei oi fIoal), and X
is lound lo lhis nunlei if il is a vaiialIe oi lesled ils equivaIence if il is a nunlei.
Iiecision depends on lhe undeiIying IioIog syslen.


Fernando Senz-Prez 1!2/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Aiilhnelic luiIl-ins have neaning onIy in lhe second aigunenl of is, lhey
cannol le used eIsevheie. Ioi exanpIe:

DES> X is sqrt(2)

{
1.4142135623730951 is sqrt(2)
}
Info: 1 tuple computed.
Heie, sqrt(2) is an aiilhnelic expiession lhal uses lhe luiIl-in funclion sqrt
(squaie iool). ul:

DES> sqrt(2) is sqrt(2)

iaises an inpul eiioi lecause an aiilhnelic expiession can onIy occui as lhe
iighl aigunenl of is. Anolhei exanpIe is:

DES> X is e

{
2.718281828459045 is exp(1)
}
Info: 1 tuple computed.

DES> e is e

{
}
Info: 0 tuples computed.
This neans lhal lhe luiIl-in aiilhnelic conslanl e cannol le used oulside of an
aiilhnelic expiession, and il is olheivise undeislood as a usei defined ieIalion. Heie,
an inpul eiioi is nol iaised since e couId le a usei defined ieIalion. In facl, lhis shouId
iaise a lype eiioi, lul lhey aie nol cuiienlIy conlioIIed.
In addilion, nole lhal aiilhnelic expiessions aie conpound leins vhich aie
liansIaled inlo an inleinaI equivaIenl iepiesenlalion. The Iasl exanpIe shovs lhis since
lhe conslanl e is liansIaled lo exp(1).
ConcIuding, lhe infix (infinile) ieIalion is is undeislood as lhe sel of paiis <V,
E> such lhal V is lhe equivaIenl vaIue lo lhe evaIualion of lhe aiilhnelicaI expiession
E. Nole lhal, since lhis ieIalion is infinile, ve nay ieach non-leininalion: Lels
considei lhe foIIoving piogian (loop.dl in lhe disliilulion diiecloiy) vilh lhe queiy
loop(X):

loop(0).
loop(X) :-
loop(Y),
X is Y + 1.
LvaIualing lhal queiy iesuIls in a non-leininaling cycIe lecause unIiniled
lupIes is(N,N+1) lecone conpuled. To shov il, liy lhe queiy, piess CliI-C, and lype


Fernando Senz-Prez 1!3/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

listing(et) al lhe IioIog pionpl (onIy vhen DLS has leen slailed fion a IioIog
inleipielei).
4.%.3 S#$ 2rit/metic
Aiilhnelic expiessions aie consliucled vilh lhe aiilhnelic opeialois Iisled in
lhe nexl seclion. They aie used in piojeclion Iisls and condilions.
4.%.4 2rit/metic 4uiltGins
This seclion conlains lhe Iislings foi lhe suppoiled aiilhnelic opeialois,
conslanls, and funclions.
4.%.4.1 2rit/metic =&erators
The foIIoving opeialois aie lhe onIy ones aIIoved in aiilhnelic expiessions,
vheie X and Y sland aIso foi aiilhnelic expiessions.
\X (ilvise negalion) I%&
ilvise negalion of lhe inlegei X.
-X (Negalive vaIue) I%&
Negalive vaIue of ils singIe aigunenl X.
X ** Y (Iovei) I%&
X iaised lo lhe povei of Y.
X ^ Y (Iovei)
Synonyn foi X ** Y.
X * Y (MuIlipIicalion) I%&
X nuIlipIied ly Y.
X / Y (ReaI division) I%&
IIoal quolienl of X and Y.
X + Y (Addilion) I%&
Sun of X and Y.
X - Y (Sulliaclion) I%&
Diffeience of X and Y.
X // Y (Inlegei quolienl) I%&
Inlegei quolienl of X and Y. The iesuIl is aIvays liuncaled lovaids zeio.
X rem Y (Inlegei ienaindei) I%&
The vaIue is lhe inlegei ienaindei aflei dividing X ly Y, i.e., integer(X)-
integer(Y)*(X//Y). The sign of a nonzeio ienaindei viII lhus le lhe sane as
lhal of lhe dividend.
X \/ Y (ilvise disjunclion) I%&
ilvise disjunclion of lhe inlegeis X and Y.
X /\ Y (ilvise conjunclion) I%&
ilvise disjunclion of lhe inlegeis X and Y.
X xor Y (ilvise excIusive oi) I%&
ilvise excIusive oi of lhe inlegeis X and Y.
X << Y (Shifl Iefl) I%&
X shifled Iefl Y pIaces.
X >> Y (Shifl iighl) I%&
X shifled iighl Y pIaces.


Fernando Senz-Prez 1!4/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

4.%.4.2 2rit/metic Constants
pi (n)
Aichinedes' conslanl.
e (Nepeiian nunlei)
Nepeiian nunlei.
4.%.4.3 2rit/metic .unctions
sqrt(X) (Squaie iool) I%&
Squaie iool of X.
log(X) (NaluiaI Iogaiilhn) I%&
Logaiilhn of X in lhe lase of lhe Nepeiian nunlei (e).
ln(X) (NaluiaI Iogaiilhn)
Synonyn foi log(X).
log(X,Y) (Logaiilhn)
Logaiilhn of Y in lhe lase of X.
sin(X) (Sine) I%&
Sine of X.
cos(X) (Cosine) I%&
Cosine of X.
tan(X) (Tangenl) I%&
Tangenl of X.
cot(X) (Colangenl)
Colangenl of X.
asin(X) (Aic sine)
Aic sine of X.
acos(X) (Aic cosine)
Aic cosine of X.
atan(X) (Aic langenl) I%&
Aic langenl of X.
acot(X) (Aic colangenl)
Aic colangenl of X.
abs(X) (AlsoIule vaIue) I%&
AlsoIule vaIue of X.
float(X) (IIoal vaIue) I%&
IIoal equivaIenl of X, if X is an inlegei, olheivise, X ilseIf.
integer(X) (Inlegei vaIue)
CIosesl inlegei lelveen X and O, if X is a fIoal, olheivise, X ilseIf.
sign(X) (Sign) I%&
Sign of X, i.e., -1, if X is negalive, O, if X is zeio, and 1, if X is posilive, coeiced inlo
lhe sane lype as X (i.e., lhe iesuIl is an inlegei, iff X is an inlegei).
gcd(X,Y) (Ciealesl connon divisoi)
Ciealesl connon divisoi of lhe lvo inlegeis X and Y.
min(X,Y) (Mininun)
Leasl vaIue of X and Y.
max(X,Y) (Maxinun)
Ciealesl vaIue of X and Y.
truncate(X) (Tiuncale) I%&
CIosesl inlegei lelveen X and O.
float_integer_part(X) (Inlegei pail as a fIoal) I%&


Fernando Senz-Prez 1!5/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The sane as float(integer(X)).
float_fractional_part(X) (IiaclionaI pail as a fIoal) I%&
IiaclionaI pail of X, i.e., X - float_integer_part(X).
round(X) (CIosesl inlegei) I%&
CIosesl inlegei lo X. X has lo le a fIoal. If X is exaclIy haIf-vay lelveen lvo
inlegeis, il is iounded up (i.e., lhe vaIue is lhe Ieasl inlegei giealei lhan X).
floor(X) (IIooi) I%&
Ciealesl inlegei Iess oi equaI lo X. X has lo le a fIoal.
ceiling(X) (CeiIing) I%&
Leasl inlegei giealei oi equaI lo X. X has lo le a fIoal.
4.%.% 1egation
not(Query) (Slialified negalion)
Il slands foi lhe conpIenenl of lhe ieIalion Query v.i.l. lhe neaning of lhe
piogian (i.e., cIosed voiId assunplion). See Seclions 4.1.8 and 5.17.3. If Query is
nol an alon, a nev piedicale defined ly a head Head vilh ieIevanl vaiialIes in
Query is luiIl, and defined ly lhe singIe iuIe Head :- Query. Then, not(Head)
iepIaces not(Query).
4.%." Datalog =uter Boins
lj(LeftRelation,RightRelation,JoinCondition) (Lefl join)
Il slands foi lhe Iefl oulei join of lhe ieIalions LeftRelation and ieIalions
RightRelation, undei lhe condilion JoinCondition (expiessed as IileiaIs, cf.
Seclion 4.1.1), as undeislood in exlended ieIalionaI aIgelia (LeftRelation
JoinCondition
RightRelation).
rj(LeftRelation,RightRelation,JoinCondition) (Righl join)
Il slands foi lhe iighl oulei join of lhe ieIalions LeftRelation and ieIalions
RightRelation, undei lhe condilion JoinCondition (expiessed as IileiaIs, cf.
Seclion 4.1.1), as undeislood in exlended ieIalionaI aIgelia (LeftRelation
JoinCondition
RightRelation).
fj(LeftRelation,RightRelation,JoinCondition) (IuII join)
Il slands foi lhe fuII oulei join of lhe ieIalions LeftRelation and ieIalions
RightRelation, undei lhe condilion JoinCondition (expiessed as IileiaIs, cf.
Seclion 4.1.1), as undeislood in exlended ieIalionaI aIgelia (LeftRelation
JoinCondition
RightRelation).
4.%.( Datalog 2ggregates
4.%.(.1 2ggregate .unctions
Aggiegale funclions can onIy occui in lhe conlexl of a group_ly aggiegale
piedicale (see nexl seclion) and appIy lo lhe iesuIl sel foi ils inpul ieIalion.
count(Variable)
Reluin lhe nunlei of lupIes so lhal lhe vaIue foi Variable is nol nuII.
count
Reluin lhe nunlei of lupIes of lhe iesuIl sel.
sum(Variable)
Reluin lhe sun of possilIe vaIues foi Variable, ignoiing nuIIs.
times(Variable)


Fernando Senz-Prez 1!6/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Reluin lhe pioducl of possilIe vaIues foi Variable, ignoiing nuIIs.
avg(Variable)
Reluin lhe aveiage of possilIe vaIues foi Variable, ignoiing nuIIs.
min(Variable)
Reluin lhe nininun vaIue foi Variable, ignoiing nuIIs.
max(Variable)
Reluin lhe naxinun vaIue foi Variable, ignoiing nuIIs.
4.%.(.2 !rou&7*y ?redicate
group_by(Query,Variables,GroupConditions)
SoIve GroupConditions in lhe conlexl of Query, luiIding gioups v.i.l. lhe
possilIe vaIues lhe vaiialIes in lhe Iisl Variables. This Iisl is specified as a IioIog
Iisl, i.e., a sequence of conna-sepaialed vaIues encIosed lelveen liackels. If lhis
Iisl is enply, lheie is onIy one gioup: lhe ansvei sel foi Query. The goaI
GroupConditions nay conlain expiessions incIuding aggiegale funclions.
4.%.(.3 2ggregate ?redicates
count(Query,Variable,Result)
Counl in Result lhe nunlei of lupIes in lhe iesuIl sel foi lhe queiy Query so lhal
Variable is a vaiialIe of Query (an alliilule of lhe iesuIl ieIalion sel) and lhis
alliilule is nol nuII. Il ieluins O if no lupIes aie found in lhe iesuIl sel.
count(Query,Result)
Counl in Result lhe lolaI nunlei of lupIes in lhe iesuIl sel foi lhe queiy Query,
disiegaiding vhelhei lhey conlain nuIIs oi nol. Il ieluins O if no lupIes aie found in
lhe iesuIl sel.
sum(Query,Variable,Result)
Sun in Result lhe nunleis in lhe iesuIl sel foi lhe queiy Query and lhe alliilule
Variable, vhich shouId occui in Query. NuIIs aie sinpIy ignoied.
times(Query,Variable,Result)
Conpule in Result lhe pioducl of aII lhe nunleis in lhe iesuIl sel foi lhe queiy
Query and lhe alliilule Variable, vhich shouId occui in Query. NuIIs aie
sinpIy ignoied.
avg(Query,Variable,Result)
Conpule in Result lhe aveiage of lhe nunleis in lhe iesuIl sel foi lhe queiy
Query and lhe alliilule Variable, vhich shouId occui in Query. NuIIs aie
sinpIy ignoied.
min(Query,Variable,Result)
Conpule in Result lhe nininun of lhe nunleis in lhe iesuIl sel foi lhe queiy
Query and lhe alliilule Variable, vhich shouId occui in Query. NuIIs aie
sinpIy ignoied. If lheie aie no such nunleis, il ieluins null.
max(Query,Variable,Result)
Conpule in Result lhe naxinun of lhe nunleis in lhe iesuIl sel foi lhe queiy
Query and lhe alliilule Variable, vhich shouId occui in Query. NuIIs aie
sinpIy ignoied. If lheie aie no such nunleis, il ieluins null.
4.%.8 Datalog 1ullGrelated ?redicates
is_null(Term)
Succeed if Term is lound lo a nuII vaIue. Il iaises an exceplion if Term is a vaiialIe.
is_not_null(Term)


Fernando Senz-Prez 1!7/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Succeed if Term is nol lound lo a nuII vaIue. Il iaises an exceplion if Term is a
vaiialIe.
4.%. Du&licates
The foIIoving luiIl-ins lake effecl vhen dupIicales aie enalIed via lhe
connand /duplicates on.
distinct(Query)
Succeed as nany lines as diffeienl giound ansveis aie conpuled foi Query.
distinct([Variables], Query)
Succeed as nany lines as diffeienl giound lupIes (luiIl vilh Variables) aie
conpuled foi Query.
4.%.1' Ao&G1 #ueries
top(N,Query)
Succeed al nosl N lines foi Query.
%. System Descri&tion
This seclion incIudes desciiplions aloul lhe conneclion lo ieIalionaI dalalase
syslens via ODC conneclions, peisislency, safely and conpulaliIily issues, souice-lo-
souice liansfoinalions, lhe decIaialive deluggeis and liaceis, lhe lalch piocessing,
syslen nessages, and finaIIy Iisls aII lhe avaiIalIe connands.
%.1 +D4MS connections 0ia =D4C
DLS piovides suppoil foi conneclions lo (ieIalionaI) dalalase nanagenenl
syslens (RDMSs) in oidei lo piovide dala souices foi ieIalions. This neans lhal a
ieIalion defined in a RDMS as a viev oi lalIe is aIIoved as any olhei ieIalion defined
via a piedicale in lhe deduclive dalalase. Then, conpuling a queiy can invoIve
conpulalions lolh in lhe deduclive infeience engine and in lhe exleinaI RDMS SQL
engine. Such ieIalions lecone fiisl-cIass cilizens in lhe deduclive dalalase and,
lheiefoie, can le queiied in DalaIog and RA. If lhe ieIalion is a viev, il viII le
piocessed ly lhe SQL engine. When an ODC conneclion is opened, aII SQL
slalenenls aie iediiecled lo such conneclion, so DLS does nol Iongei piocess such
slalenenls. This neans lhal aII lhe SQL fealuies of lhe connecled RDMS aie avaiIalIe.
AInosl any ieIalionaI dalalase (RD) can le accessed fion DLS using an
ODC conneclion. ReIalionaI dalalase nanagenenl syslen (RDMS) nanufacluieis
piovide ODC inpIenenlalions vhich iun on nany opeialing syslens (Miciosofl
Windovs, Linux, Mac OS X, ...) RDMSs incIude enleipiise RDMS (as OiacIe,
MySQL, D2, ...) and desklop RDMS (as MS Access and IiIeMakei).
ODC diiveis aie usuaIIy lundIed vilh OS pIalfoins, as Windovs OSs (ODC
inpIenenlalion), Linux OS disliilulions as Ulunlu, Red Hal and Mandiiva
(UnixODC inpIenenlalion), and Mac OSs 1O' (iODC inpIenenlalion). Hovevei,
addilionaI diiveis foi specific dalalases aie needed lo le inslaIIed.
Since each RDMS piovides an ODC diivei and each OS an ODC
inpIenenlalion, delaiIs on hov lo configuie such conneclions aie oul of lhe scope of
lhis nanuaI. Hovevei, lo configuie such a conneclion, lypicaIIy, lhe ODC diivei is


Fernando Senz-Prez 1!8/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Iooked foi and inslaIIed in lhe OS. Then, foIIoving lhe nanufacluiei
ieconnendalions, il is configuied. You can find nany vel pages vilh advice on lhis.
Heie, ve assune lhal lheie aie ODC conneclions aIieady avaiIalIe.
%.1.1 =&ening an =D4C Connection
To access a RD in DLS, fiisl open lhe conneclion vilh lhe foIIoving connand,
vheie test is lhe nane of a pieviousIy ciealed ODC conneclion lo a dalalase:

DES-SQL> /open_db test
You can aIso piovide a usei nane and passvoid (if needed) as in:

DES-SQL> /open_db test user(smith) password(my_pwd)
If ODC connecloi ieluins an eiioi, lhen you have lo encIose lhese lelveen
aposliophes (') as in:

DES-SQL> /open_db test user('smith') password('my_pwd')
Nole lhal if you have pieviousIy ciealed sone dalalase oljecls (lalIes, vievs,
...) in DLS vilhoul an ODC conneclion, lhey aie sliII avaiIalIe and can le queiied loo
(foi noie infoinalion see Seclion 5.1.7).
%.1.2 Using a Connection
Assuning lhal lhe conneclion Iinks lo an enply dalalase, Iel's slail ciealing
sone dalalase oljecls:
(Nole lhal, depending on lhe inslaIIed MySQL ODC diivei veision, annoying
nessages nighl le dispIayed.)

DES-SQL> create table t(a varchar(20) primary key)
DES-SQL> create table s(a varchar(20) primary key)
DES-SQL> create view v(a,b) as select * from t,s
DES-SQL> insert into t values(1)
Info: 1 tuple inserted.
DES-SQL> insert into s select * from t
Info: 1 tuple inserted.
DES-SQL> insert into s values(2)
Info: 1 tuple inserted.
Nexl, one can ask foi lhe dalalase schena (neladala) vilh lhe connand:

DES-SQL> /dbschema
Info: Table(s):
* s(a:varchar)
* t(a:varchar)
Info: View(s):
* v(a:varchar,b:varchar)
AII of lhese lalIes and vievs can le accessed fion DLS, as if lhey veie IocaI:

DES-SQL> select * from s;
answer(a:varchar) ->
{


Fernando Senz-Prez 1!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

answer('1'),
answer('2')
}
Info: 2 tuples computed.

DES-SQL> select * from t;
answer(a:varchar) ->
{
answer('1')
}
Info: 1 tuple computed.

DES-SQL> select * from v;
answer(a:varchar,b:varchar) ->
{
answer('1','1'),
answer('1','2')
}
Info: 2 tuples computed.

DES-SQL> insert into t values('1')
Exception: error(odbc(23000,1062,[MySQL][ODBC 3.51
Driver][mysqld-5.0.41-community-nt]Duplicate entry '1' for key
1),_G3)
In lhis exanpIe, as lalIe t has ils singIe coIunn defined as ils piinaiy key,
liying lo inseil a dupIicale enliy iesuIls in an exceplion fion lhe ODC diivei.
Inlegiily consliainls aie handIed ly lhe RDMS connecled, inslead of DLS (nolice lhal
lhe exceplion nessage is diffeienl fion lhe one geneialed ly DLS).
Moieovei, you can sulnil SQL slalenenls lhal aie nol suppoiled ly DLS lul
olheivise ly lhe connecled RDMS, as:

DES-SQL> alter table t drop primary key;
Then, you can inseil again and see lhe iesuIl (incIuding dupIicales):

DES-SQL> insert into t values('1')
Info: 1 tuple inserted.

DES-SQL> select * from v;
answer(a:varchar,b:varchar) ->
{
answer('1','1'),
answer('1','1'),
answer('1','2'),
answer('1','2')
}
Info: 4 tuples computed.
AIso, dupIicale ienoving is aIso possilIe ly lhe exleinaI RDMS:

DES-SQL> select distinct * from v;
answer(a:varchar,b:varchar) ->
{
answer('1','1'),


Fernando Senz-Prez 11!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

answer('1','2')
}
Info: 2 tuples computed.
NonelheIess, lhese exleinaI oljecls can le accessed fion DalaIog as veII (pIease
ienenlei lo enalIe dupIicales lo gel lhe expecled iesuIl):

DES-SQL> /datalog
DES> /duplicates on
Info: Duplicates are on.
DES> s(X),t(X)
Info: Processing:
answer(X) :-
s(X),
t(X).
{
answer('1'),
answer('1')
}
Info: 2 tuples computed.
This is equivaIenl lo lhe foIIoving SQL slalenenl:

DES> select s.a from s,t where s.a=t.a
answer(a:varchar) ->
{
answer('1'),
answer('1')
}
Info: 2 tuples computed.
Hovevei, vhiIsl lhe foinei has leen piocessed ly lhe DalaIog engine, lhe
Iallei has leen piocessed ly lhe exleinaI RDMS. So, sone conpIex SQL slalenenls
nighl le noie efficienlIy piocessed ly lhe exleinaI RDMS.
DupIicales aie ieIevanl in a nunlei of silualions. Ioi inslance, considei lhe
foIIoving, vheie dupIicales aie iniliaIIy disalIed:

DES> group_by(v(X,Y),[X,Y],C=count)
Info: Processing:
answer(X,Y,C) :-
group_by(v(X,Y),[X,Y],C = count).
{
answer('1','1',1),
answer('1','2',1)
}
Info: 2 tuples computed.
AIlhough lheie aie a coupIe of lupIes foi each gioup (see lhe lalIe conlenls
alove), onIy one is ieluined in lhe counl lecause lhey aie indislinguishalIe in a sel.
Nov, if dupIicales aie aIIoved, ve gel lhe expecled iesuIl:

DES> /duplicates on
Info: Duplicates are on.

DES> group_by(v(X,Y),[X,Y],C=count)


Fernando Senz-Prez 111/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Info: Processing:
answer(X,Y,C) :-
group_by(v(X,Y),[X,Y],C = count).
{
answer('1','1',2),
answer('1','2',2)
}
Info: 2 tuples computed.
Nole lhal, even vhen you can access SQL oljecls fion DalaIog, lhe conliaiy is
nol aIIoved lecause lheie is noi DalaIog neladala infoinalion foi lhe exleinaI SQL
engine, neilhei access lo DalaIog dala. The dala liidge is onIy opened fion DLS lo lhe
exleinaI DMS, nol lhe olhei vay iound. This is in conliasl lo lhe SQL dalalase
inleinaIIy piovided ly DLS, vhich aIIovs a lidiieclionaI connunicalion since lype
infoinalion is suppoiled foi DalaIog piedicales.
%.1.3 =&ening Se0eral Connections
Iion ieIease 3.O on, seveiaI OCC conneclions can le opened sinuIlaneousIy.
Lach line a nev conneclion is opened, il lecones lhe nev cuiienl conneclion, and aII
queiy piocessing is ieIaled lo il ly defauIl. Ioi inslance, lo inspecl (a ialhei Iiniled sel
of) neladala, one can sulnil lhe foIIoving connand:

DES> /open_db mysql
DES> /dbschema
Info: Database 'mysql'
Info: Table(s):
* s(a:varchar(20))
* t(a:integer(4))
* w(a:varchar(20))
Info: View(s):
* v(a:varbinary(20))
Info: No integrity constraints.
To Iisl aII lhe opened conneclions, use lhe connand:

DES> /show_dbs
$des
access
csv
db2
excel
mysql
oracle
postgresql
sqlserver
vheie you can see lhe Iisl of opened conneclions, slailing vilh $des, vhich is lhe
defauIl dalalase (DLS deduclive engine). You can cIose aII conneclions lul lhe defauIl
one. As lhe nanes suggesl, you can open a vide iange of dala souices, nol onIy fion
dalalase nanagenenl syslens as D2, OiacIe, SQL Seivei lul aIso fion olhei souices
as dalasheels (LxceI) and lexl fiIes (CSV (conna-sepaialed vaIues) fiIes). Ioi defining a
"lalIe" in MS LxceI, you shouId use Inseil -> Nane -> Define, vheie you specify lhe
nane of lhe lalIe and lhe ceII iange il coveis (vheie fiisl iov can le used as fieId


Fernando Senz-Prez 112/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

nanes, oplionaIIy). Types aie infeiied ly lhe LxceI syslen. SiniIaiIy, vhen defining a
conneclion lo a lexl fiIe, fieId nanes can le lhose in lhe fiisl Iine of expIicilIy given.
Again, lypes aie infeiied. In lolh cases, you can inspecl lhe "dalalase" schena and
queiy lhen vilh eilhei SQL slalenenls, oi DalaIog queiies oi RA expiessions.
Nole lhal sone dala souices do neilhei ciealing vievs noi consliainls, such as
dalasheels and lexl fiIes.
A vaining foi nevlies: You have lo define conneclion nanes foIIoving ODC
inslaIIalion, do nol expecl lhe ones Iisled alove aie piovided ly defauIl, you need lolh
lhe ODC conneclion and lhe dala piovidei (dalalase seivei oi vhalevei) aIieady
inslaIIed and configuied.
%.1.4 Current Connection
To find oul lhe cuiienl opened ODC dalalase, use lhe connand:

DES-SQL> /current_db
%.1.% Ma-ing a Connection t/e Current =ne
Making a given conneclion lhe cuiienl one is sinpIy done vilh:

DES-SQL> /use_db access
vheie access is an exanpIe of an aIieady opened conneclion nane.
%.1." Closing a Connection
CIosing lhe cuiienl conneclion is sinpIy done vilh:

DES-SQL> /close_db
You can aIso specify lo cIose a given conneclion, as in:

DES-SQL> /close_db access
%.1.( Sc/ema and Data Visi*ility
Any sulnilled queiy oi connand iefei lo lhe cuiienl conneclion if nol
olheivise specified as an aigunenl of a connand. When opening a conneclion (and
aulonalicaIIy naking il lhe cuiienl one), lheii dala and schena aie visilIe, lul nol lhe
dala and schena of olhei aIieady opened conneclions. In conliasl, dala fion lhe
defauIl deduclive dalalase aie visilIe foi DalaIog and RA queiies, aIlhough ils schena
does nol. RecaII lhal you can cieale lalIes and vievs in lhe defauIl dalalase, vhich
viII le handIed ly DLS lul nol piojecled lo any exleinaI dalalase (unIess you peisisl a
piedicale, see Seclion 5.2). Anyvay, dala fion lhe defauIl deduclive dalalase ($des)
aie not visilIe foi SQL slalenenls foi a cuiienl conneclion olhei lhan $des, as lhey aie
sulnilled foi piocessing lo lhe exleinaI dalalase.
In lhe foIIoving syslen session, one cieales a lalIe in lhe defauIl dalalase of
DLS (DD), inseils a vaIue, opens a conneclion, and ieaIize lhal lhe lalIe schena is nol
visilIe, lul ils dala do. This cones fion lhe facl lhal, fiisl, SQL dala is liansIaled ly
DLS lo DalaIog dala and, second, DalaIog dala can le seanIessIy conlined vilh
exleinaI dalalases (LD).


Fernando Senz-Prez 113/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


DES> create table t(a int)
Cieale lalIe t in DD
DES> insert into t values(1)
Info: 1 tuple inserted.
Inseil t(1) in DD
DES> select * from t
answer(t.a:number(integer)) ->
{
answer(1)
}
Info: 1 tuple computed.
SeIecl dala fion DD
DES> /open_db mysql
Open an LD
DES> select * from t
Error: ODBC Code (1146):
[MySQL][ODBC 5.1 Driver][mysqld-
5.5.9]Table 'test.t' doesn't exist
SeIecl dala fion LD
As t is nol defined in LD,
lhen, eiioi
DES> t(X)
{
t(1)
}
Info: 1 tuple computed.
Iiedicale l is knovn lo DD and
can le queiied fion DalaIog

In lhis vay, you can aIso conline dala fion DLS and lhe exleinaI dala souice.
Nexl syslen session exanpIe shovs lhis ly ciealing a nev lalIe in lhe exleinaI
dalalase and conlining alove piedicale t/1, defined in DD, vilh a nev lalIe s
ciealed in LD:

DES> create table s(a int)
Cieale lalIe s in LD
DES> insert into s values(2)
Info: 1 tuple inserted.
Inseil s(2) in LD
DES> select * from s
answer(a:integer(4)) ->
{
answer(2)
}
Info: 1 tuple computed.
SeIecl dala fion LD.
Nole lhe diffeienl lype v.i.l. DD
DES> t(X),s(Y)
Info: Processing:
answer(X,Y) :-
t(X),
s(Y).
{
answer(1,2)
}
Info: 1 tuple computed.
}oin t/1 (DD) vilh s/1 (LD)

%.1.8 Sol0ing Engine and =D4C connections
When lhe cuiienl dalalase is an open ODC conneclion, any slalenenl is
sulnilled lo lhe exleinaI dalalase foi ils soIving ly defauIl. Hovevei, lhis lehavioi
can le changed ly foicing DLS lo soIve SQL DQL queiies sulnilled lo an exleinaI
dalalase. This aIIovs lo expeiinenl vilh noie expiessive foins of SQL queiies as


Fernando Senz-Prez 114/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

aIIoved ly lhe IocaI deduclive engine, as hypolhelicaI queiies, non-Iineai and
nuluaIIy iecuisive queiies.
To foice a singIe SQL DQL queiy lo le piocessed ly DLS, sinpIy use lhe
connand /des foIIoved ly lhe queiy. Nole hovevei lhal DML and DDL queiies aie
sliII senl lo lhe exleinaI DMS. Lel's considei MySQL, vhich does nol suppoil
iecuisive queiies up lo ils cuiienl veision 5.5. If ve had avaiIalIe lhe lalIe edge(a
int, b int), ve can conpule ils liansilive cIosuie as foIIovs:

DES> /open_db mysql
DES> select * from edge
answer(a:integer(4),b:integer(4)) ->
{
answer(1,2),
answer(2,3),
answer(3,4)
}
Info: 3 tuples computed.
DES> /des assume select e1.a,e2.b from edge e1, edge e2 where
e1.b=e2.a in edge(a,b) select * from edge
answer(edge.a:number(integer),edge.b:number(integer)) ->
{
answer(1,2),
answer(1,3),
answer(1,4),
answer(2,3),
answer(2,4),
answer(3,4)
}
Info: 6 tuples computed.
%.1. Integrity ConstraintsI =D4C ConnectionsI and ?ersistency
Inlegiily consliainls as desciiled in Seclion 4.1.15 aie noniloied ly DLS foi lhe
IocaI deduclive dalalase. This neans lhal inseiling vaIues diieclIy inlo exleinaI lalIes
(eilhei ly sulnilling an INSERT INTO slalenenl fion lhe opened conneclion oi ly
inseiling vaIues oul of DLS) is nol noniloied foi consliainl consislency. Hovevei, as
consliainl consislency checking consideis aII visilIe dala, vhen asseiling inlo lhe IocaI
dalalase, dala fion lhe cuiienl opened conneclion is aIso laken inlo accounl. The
foIIoving syslen session shovs a possilIe scenaiio iIIuslialing lhese silualions:

DES> /use_db $des
DES> create or replace table t(a int primary key)
DES> /dbschema
Info: Database '$des'
Info: Table(s):
* t(a:number(integer))
- PK: [a]
Info: No views.
Info: No integrity constraints.
DES> /open_db mysql
TalIe 't' is aIso an exleinaI lalIe in conneclion 'mysql':



Fernando Senz-Prez 115/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> /dbschema t
Info: Database 'mysql'
Info: Table:
* t(a:integer(4))
Reliieve lupIes fion exleinaI lalIe 't':

DES> select * from t
answer(a:integer(4)) ->
{
}
Info: 0 tuples computed.
The foIIoving is inseiled in exleinaI lalIe 't'. RecaII lhal SQL slalenenls undei
an opened conneclion aie sulnilled diieclIy lo lhe exleinaI RDMS:

DES> insert into t values (1)
Info: 1 tuple inserted.
DES> insert into t values (1) % Not rejected as it is not
monitored by DES
Info: 1 tuple inserted.
DLS does noniloi lhe foIIoving asseilion as il is diiecled lo lhe IocaI dalalase:

DES> /assert t(1)
Error: Primary key violation t.[a]
when trying to insert: t(1)
Error: Asserting rules due to integrity constraint violation.
DES> /use_db $des
When lhe cuiienl dalalase is lhe IocaI dalalase ('$des'), lhe exleinaI lalIe 't' is
nol visilIe. So, lhe foIIoving facl is asseiled in lhe IocaI dalalase:

DES> insert into t values (1)
Info: 1 tuple inserted.
Any olhei allenpl lo asseil lhe sane facl t(1) is iejecled

DES> /assert t(1)
Error: Primary key violation t.[a]
when trying to insert: t(1)
Error: Asserting rules due to integrity constraint violation.
The foIIoving vouId aIso go lo lhe IocaI dalalase:

DES> insert into t values (1)
Error: Primary key violation t.[a]
when trying to insert: t(1)
Error: Asserting rules due to integrity constraint violation.
Info: 0 tuples inserted.
IinaIIy, any peisisled piedicale (see Seclion 5.2) vhich has allached consliainls
is checked foi ils consislency, iiiespeclive of lhe exleinaI dalalase il is sloied. AIso,
any of lhe suppoiled consliainls can le allached lo peisislenl piedicales, lheiefoie
pioviding a high expiessivily and decIaialive consislency IeveI.


Fernando Senz-Prez 116/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

%.1.1' Ca0eats and $imitations
This seclion Iisls sone caveals and Iinilalions of lhe cuiienl inpIenenlalion of
ODC conneclions lo exleinaI dala souices.
%.1.1'.1 Cac/ing
Dala in ieIalionaI lalIes aie cached in lhe neno lalIe duiing DalaIog
conpulalions, and il is nol iequesled anynoie unliI lhis cache is cIeaied (eilhei
expIicilIy vilh lhe connand /clear_et oi lecause a connand oi slalenenl
invaIidaling ils conlenls, as an SQL updale queiy). Theiefoie, il couId le possilIe lo
access ouldaled dala fion a DalaIog queiy. Lel's considei:

DES-SQL> /datalog t(X)
{
t('1')
}
Info: 1 tuple computed.
Then, fion lhe MySQL cIienl:

mysql> insert into t values('2');
Query OK, 1 row affected (0.06 sec)
And, aflei, in DLS, lhe nev lupIe is nol Iisled via a DalaIog queiy:

DES-SQL> /datalog t(X)
{
t('1')
}
Info: 1 tuple computed.
Hovevei, an SQL slalenenl ieluins lhe coiiecl ansvei:

DES-SQL> select * from t;
answer(a:varchar) ->
{
answer('1'),
answer('2')
}
Info: 2 tuples computed.
In addilion, il is nol ieconnended lo nix DalaIog and SQL dala. Il is possilIe
lo asseil lupIes vilh lhe sane nane and aiily as exisling RDMS's lalIes and/oi
vievs. Lel's considei lhe sane lalIe l as alove vilh lhe sane dala (lvo lupIes t('1')
and t('2')) and asseil a lupIe t('3') as foIIovs:

DES-SQL> /assert t('3')

DES-SQL> /datalog t(X)
{
t('1'),
t('2'),
t('3')
}
Info: 3 tuples computed.


Fernando Senz-Prez 117/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


DES-SQL> select * from t
answer(a:varchar) ->
{
answer('1'),
answer('2')
}
Info: 2 tuples computed.
This ieveaIs lhal, aIlhough on lhe DLS side, DalaIog dala aie knovn, il is nol on
lhe RDMS side. This is in conliasl lo lhe DLS nanagenenl of dala: if no ODC
conneclion is opened, lhe DLS engine is avaie of any changes lo dala, lolh fion
DalaIog and SQL sides.
ConcIuding, lhose updales lhal aie exleinaI lo DLS nighl nol le noliced ly lhe
DLS engine. And, aIso, an ODC conneclion shouId le seen as a souice of exleinaI dala
lhal shouId nol le nixed vilh DalaIog dala. Hovevei, you can safeIy use lhe noie
poveifuI DalaIog Ianguage lo queiy exleinaI dala (and lo le suie lhe cuiienl dala is
ieliieved, cIeai lhe cache vilh /clear_et).
%.1.1'.2 =D4C Metadata
When conpuling lhe piedicale dependency giaph and slialificalion, neladala
fion lhe exleinaI DMS is ieliieved, vhich can le a coslIy opeialion if lhe nunlei of
lalIes and vievs is Iaige. This is lhe defauIl case vhen opening conneclions lo DMSs
as SQL Seivei oi OiacIe, vheie nany vievs aie defined foi an enply dalalase. AIso,
ODC conneclions lo OiacIe seen lo le sIov.
Lisling lhe dalalase schena can suffei lhis silualion as veII, ly issuing lhe
connand /dbschema. Inslead, il is lellei lo focus on lhe iequiied oljecl lo dispIay, as
eilhei /dbschema relname oi /dbschema connection:relname.
%.1.1'.3 =D4C $imitations
As piedicale dependency giaphs aie nol conpuled fion exleinaI dala souices,
seveiaI fealuies aie nol suppoiled in lhe conlexl of an opened ODC conneclion:
SQL liacei
Tesl case geneialoi
%.1.1'.4 ?lat:ormGs&eci:ic Issues
ODC conneclions aie onIy suppoiled ly lhe piovided linaiies, and lhe souice
disliilulions foi SWI-IioIog and SICSlus IioIog.
If you use a 64 lil Windovs OS, nolice lhal you can seIecl lo iun eilhei a 64 lil
veision of DLS oi a 32 lil one (linaiies luiIl vilh SWI-IioIog aie piovided in lhe
dovnIoad aiea). In lhe fiisl case (64 lil), you nusl use lhe Dalalase Conneclivily
(ODC) Dala Souice Adninislialoi looI (Odlcad32.exe):
- The 32-lil veision of lhe Odlcad32.exe fiIe is Iocaled in lhe
syslendiiveWindovsSysWoW64 foIdei.
- The 64-lil veision of lhe Odlcad32.exe fiIe is Iocaled in lhe
syslendiiveWindovsSyslen32 foIdei.
AIso nolice lhal a 64 lil diivei iequiies aIso a 64 lil dalalase inslaIIalion. Ioi
inslance, you can define a 32 lil ODC conneclion lo 32 lil MS Access inslaIIalion and


Fernando Senz-Prez 118/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

a 64 lil ODC conneclion lo a 64 lil OiacIe inslaIIalion. In lhis scenaiio, lolh
conneclinos cannol le opened fion lhe sane DLS inslance (vhich is eilhei a 32 lil oi
64 lil ieIease).
%.1.11 Aested =D4C Dri0ers
SeveiaI dala souices have leen successfuIIy lesled on Windovs XI/Visla/7 32
lil vilh lolh SICSlus IioIog and SWI-IioIog execulalIes and souices:
IM D2 v9.7.2OO.358
OiacIe Dalalase Lxpiess Ldilion 11g ReIease 2 (aIso lesled vilh Windovs 7 64 lil
and SWI-IioIog 6.O.O 64 lil)
SQL Seivei Lxpiess 2OO8 (incIuding spaliaI conponenls)
MySQL 5.5.9
IoslgieSQL 9.1.3
Access 2OO3
LxceI 2OO3
CSV lexl fiIes
%.2 ?ersistency
Since DLS 3.O, il is possilIe lo nake piedicales peisisl on eilhei an exleinaI
dalalase, oi dalasheel oi lexl fiIe, i.e., any dala souice suppoiled ly an ODC
conneclion. This seclions desciiles hov lo peisisl a piedicale, use il, exanine ils
schena, unpeisisl il, and aIso Iisls a coupIe of caveals.
%.2.1 ?ersisting a ?redicate
An asseilion is used lo decIaie a peisisled piedicale, as in:

DES> :-persistent(p(a:int),mysql)
vheie ils fiisl aigunenl is lhe piedicale and ils schena, and lhe second one is lhe
ODC conneclion nane. This nane can le onilled if lhe cuiienl conneclion is lhe one
you vanl lo use lo peisisl lhe piedicale, as in:

DES> /current_db
Info: Current database is 'mysql'. DBMS: mysql
DES> :-persistent(p(a:int))
You can confiin lhal piedicale p has leen decIaied as peisislenl vilh:

DES> /list_persistent
mysql:p(a:number(integer))
vheie lhe conneclion nane is shovn, foIIoved ly a senicoIon and lhe piedicale
schena.
AIso, if you have lype infoinalion decIaied aIieady, you can sinpIy iefei lo lhe
piedicale vilh ils nane and aiily in lhe peisislency asseilion:



Fernando Senz-Prez 11/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> /use_db $des
DES> create table p(a int)
DES> /use_db mysql
DES> :-persistent(p/1)
DES> /list_persistent
mysql:p(a:number(integer))
The geneiaI foin of a peisislency asseilion is as foIIovs:
:-persistent(PredSpec[,Connection]))
This asseilion nakes a piedicale lo peisisl on an exleinaI RDMS via an ODC
conneclion. PredSpec can le eilhei lhe pallein PredName/Arity oi
PredName(Schema), vheie Schema can le eilhei ArgName1, , ArgNameN oi
ArgName1:Type1, , ArgNameN:TypeN. If a conneclion nane is nol piovided, lhe
cuiienl open dalalase is used. The IocaI, defauIl dalalase $des cannol le used lo
peisisl, lul an ODC conneclion.
%.2.2 Using ?ersistent ?redicates
You can asseil facls as usuaI and queiy lhe peisisled piedicale p/1 as lhe
foIIoving exanpIe shovs:

DES> /assert p(1)
DES> p(X)
{
p(1)
}
Info: 1 tuple computed.
And, as expecled, il can seanIessIy le conlined vilh olhei non-peisislenl
piedicales, as in:

DES> /assert q(2)
DES> p(X),q(Y),X<Y
Info: Processing:
answer(X,Y) :-
p(X),
q(Y),
X < Y.
{
answer(1,2)
}
Info: 1 tuple computed.
vheie q(2) is in lhe neaning of q/1.
AIso, you can use SQL oi RA Ianguages lo queiy such peisislenl piedicales, as
in:

DES> :-type(q(a:int))
DES> select * from p,q where p.a<q.a
answer(p.a:number(integer),q.a:number(integer)) ->
{
answer(1,2)
}


Fernando Senz-Prez 12!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Info: 1 tuple computed.
DES> p zjoin p.a<q.a q
answer(p.a:number(integer),q.a:number(integer)) ->
{
answer(1,2)
}
Info: 1 tuple computed.
And peisislenl piedicales can le conlined even vilh exleinaI dala coning
fion olhei ODC conneclion, as in:

DES> /open_db access
DES> /dbschema t
Info: Database 'access'
Info: Table:
* t(a:INTEGER(4))
DES> p(X),t(X)
Info: Processing:
answer(X) :-
p(X),
t(X).
{
answer(1)
}
Info: 1 tuple computed.
Heie, lhe cuiienl dalalase is access and aII ils dala is avaiIalIe (as aIieady
inlioduced in Seclion 5.1.2), in pailicuIai, lhe lalIe t, vhich conlains in pailicuIai lhe
lupIe t(1).
As veII, one can ieliacl lhe iuIes pieviousIy asseiled. Ioi inslance:

DES> /retract p(1)
DES> /retract p(X):-r(X)
%.2.3 ?rocessing a ?ersistency 2ssertion
Iiocessing a peisislency asseilion neans lo nake peisislenl a piedicale, i.e., aII
of ils cuiienl iuIes as veII as iuIes added afleivaids aie sloied in a peisislenl nedia,
as a ieIalionaI dalalase. A facl is piojecled lo a lalIe vheieas a iuIe is liansIaled inlo
an SQL viev. Lach peisisled piedicale is liansIaled inlo a lalIe foi hoIding such facls
and a viev vhich is lhe union of aII lhe SQL liansIalions foi ils iuIes. TiansIaling iuIes
inlo SQL vievs incIudes an adaplalion of DiaxIei's IioIog lo SQL conpiIei |Diax92j.
Any iuIe leIonging lo lhe definilion of a piedicale pred vhich is leing nade
peisislenl is expecled, in geneiaI, lo invoIve caIIs lo olhei piedicales. Lach caIIee (such
olhei caIIed piedicale ) can le:
An exisling ieIalion in lhe exleinaI dalalase.
An aIieady peisisled piedicale vhich is Ioaded in lhe IocaI dalalase.
An aIieady peisisled piedicale vhich is nol yel Ioaded in lhe IocaI dalalase.
A piedicale vhich has nol leen nade peisislenl yel.


Fernando Senz-Prez 121/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Ioi lhe fiisl lvo cases, lesides naking pred peisislenl, nolhing eIse is
peifoined vhen piocessing ils peisislency asseilion.
Ioi lhe lhiid case, a peisislenl piedicale is aulonalicaIIy iesloied in lhe IocaI
dalalase (c.f. nexl seclion), i.e., il is nade avaiIalIe lo lhe deduclive engine.
Ioi lhe fouilh case, each non-peisislenl piedicale is aulonalicaIIy nade
peisislenl, if possilIe, infeiiing ils lypes. This is needed in oidei foi lhe exleinaI
dalalase lo le avaie of a piedicale vhich is onIy knovn ly lhe deduclive engine so
fai, as lhis dalalase viII evenluaIIy conpule pred.
Hovevei, nol aII iuIes can le exleinaIIy piocessed foi a nunlei of ieasons
incIuding lhal lhe exleinaI dalalase does nol suppoil sone fealuies, and lhe
liansIalions of sone luiIl-ins aie nol suppoiled yel. In lhe cuiienl slale of lhe
inpIenenlalion, lhe foIIoving condilions nusl hoId foi a iuIe lo le exleinaIIy
piocessed:
The iuIe does nol conlain caIIs lo luiIl-ins lul conpaiison opeialois.
The iuIe does nol foin a iecuisive cycIe.
NonelheIess, lhey aie kepl in lhe in-nenoiy dalalase foi conpuling lhe
neaning of lhe piedicale vhen needed. This is peifoined ly lhe deduclive engine,
vhich coupIes lhe piocessing of lhe exleinaI dalalase vilh ils ovn piocessing lo
deiive lhe neaning of lhe piedicale. Theiefoie, aII lhe deduclive conpuling povei is
pieseived aIlhough lhe exleinaI peisislenl nedia Iacks sone fealuies as, foi inslance,
iecuision (lhink of MySQL and MS Access). Anyvay, such iuIes vhich aie nol
piojecled lo lhe exleinaI dalalase aie sloied on il as neladala infoinalion. This is
needed lo iesloie lhe conpIele definilion of a peisislenl piedicale upon iesloiing (c.f.
nexl seclion). Iuilhei ieIeases nighl conlain ieIaxed condilions.
Any line a piedicale is nade peisislenl, ils associaled conneclion is opened if il
nol vas opened aIieady (lhe cuiienl conneclion is nol changed, anyvay). The
conneclion is nol cIosed even vhen you diop lhe asseilion (see Seclion 5.2.6).
%.2.4 +estoring ?redicates
As expecled, if you nake a piedicale peisislenl and quil DLS, in a nexl session
you can iecovei lhe slale of lhis piedicale. Il is sinpIy done ly sulnilling again lhe
sane asseilion as used lo nake lhe piedicale peisisl foi lhe fiisl line.
Hovevei, nole lhal any iuIe in lhe in-nenoiy dalalase foi such a piedicale
viII le peisisled, loo. This is lo say lhal, foi inslance, if you have peisisled aIieady a
piedicale vhich is nol Ioaded aIieady, and you have a iuIe asseiled in lhe in-nenoiy
dalalase foi lhis piedicale, lhen lhe iesuIl of iesloiing il is lhe union of lhe asseiled
iuIe and lhe iuIes in lhe exleinaI dalalase. Ioi inslance, Iel's considei lhe foIIoving
syslen session:

DES> :-persistent(p(a:int),mysql)
DES> /assert p(1)
Nov, Iel's assune anolhei syslen session (quil and ieslail DLS):

DES> /assert p(2)
DES> :-persistent(p(a:int),mysql)
Info: Recovering existing data from external database for 'p'...


Fernando Senz-Prez 122/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> /listing
p(1).
p(2).
Info: 2 rules listed.
As il can le seen, lhe iesuIling dalalase is conposed of lhe union of lhe
exleinaI iuIes and lhe IocaI iuIes.
IinaIIy, iesloiing conpiIed iuIes in a diffeienl syslen session does nol iecovei
souice iuIes as lhey veie oiiginaIIy asseiled. They aie onIy iecoveied "as is" (i.e.,
conpiIed foin and vilhoul lexluaI vaiialIe nanes as lhey veie oiiginaIIy lyped) in
lhe sane syslen session. Lel's considei lhe foIIoving:

DES> :-persistent(p(a:int),mysql)
DES> /assert p(X):-X=1;X=2
DES> /listing
p(X) :-
X = 1
;
X = 2.
Info: 1 rule listed.
DES> /drop_assertion :-persistent(p(a:int),mysql)
DES> /listing
p(X) :-
X = 1
;
X = 2.
Info: 1 rule listed.
DES> :-persistent(p(a:int),mysql)
DES> /listing
p(X) :-
X = 1
;
X = 2.
Info: 1 rule listed.
DES> /quit
Then, ve open a nev syslen session and lype:

DES> :-persistent(p(a:int),mysql)
Info: Recovering existing data from external database...
DES> /listing
p(A) :-
A = 2.
p(A) :-
A = 1.
Info: 2 rules listed.
As can le seen, lvo iuIes aie lhe iesuIl of lhe conpiIalion of lhe oiiginaIIy
asseiled singIe iuIe vilh a disjunclive lody. AIso oiiginaI vaiialIe nanes (onIy X in
lnis case) aie nissing. Hovevei, a nexl ieIease of DLS nighl deaI vilh lhis, aIIoving lo
iesloie lhe veiy sane iuIes as lhe oiiginaI ones.
%.2.% Sc/ema o: ?ersistent ?redicates
You can iequesl lhe cuiienl dalalase schena vilh:


Fernando Senz-Prez 123/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


DES> /dbschema
Info: Database '$des'
Info: No tables.
Info: View(s):
* p(a:number(integer))
- Defining SQL statement:
CREATE VIEW p(a) AS
SELECT ALL *
FROM
p_des_table;
- Datalog equivalent rules:
Info: No integrity constraints.
vheie lhe peisisled piedicale is Iisled in lhe dalalase schena of lhe defauIl dalalase
$des and, lheiefoie, il can le conlined in a queiy vilh any piedicale visilIe in lhis
dalalase.
Nole lhal piedicale p has leen decIaied as a viev depending on a lalIe (vilh
lhe sane nane as lhe piedicale and viev, lul ending vilh "_des_table"). Since
piedicales aie defined in geneiaI vilh inlensionaI iuIes, lhe viev p viII conlain lhose
inlensionaI iuIes vheieas lhe lalIe viII conlain lhe exlensionaI iuIes (facls). Ioi
inslance, assuning lhal lhe piedicale r has leen nade peisisled aIieady in lhe sane
conneclion, ve asseil an inlensionaI iuIe foi p, and exanine ils schena:

DES> /assert p(X):-r(X)
DES> /dbschema p
Info: Database '$des'
Info: View:
* p(a:number(integer))
- Defining SQL statement:
CREATE VIEW p(a) AS
(
SELECT ALL *
FROM
p_des_table
)
UNION ALL
(
SELECT ALL rel1.a
FROM
r AS rel1
);
- Datalog equivalent rules:
p(1).
p(2).
p(X) :-
r(X).
If you change lhe cuiienl dalalase lo lhe exleinaI one and iequesl lhe schena
foi p, you gel:

DES> /use_db mysql
DES> /dbschema p
Info: Database 'mysql'


Fernando Senz-Prez 124/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Info: View:
* p(a:integer(4))
vhich is lhe schena of viev p as piovided ly lhe exleinaI dalalase syslen. Nov, lhe
delaiIed neladala infoinalion suppIied ly $des is nol avaiIalIe in lhe exleinaI
dalalase.
AIso nole lhal lhe alove coupIe of connands can le sinpIy viillen as a singIe
one vilhoul iesoiling lo change lhe cuiienl dalalase, vilh:

DES> /dbschema mysql:p
%.2." +emo0ing ?redicate ?ersistency
IinaIIy, one can unpeisisl a given piedicale ly sinpIy diopping ils asseilion, as
in:

DES> /drop_assertion :-persistent(p(a:int),mysql)
This ieliieves aII lhe dala sloied in lhe exleinaI dalalase and sloies il lack in
lhe in-nenoiy dalalase of DLS. In addilion lo lhe viev p and lalIe p_des_table
ciealed in lhe exleinaI dalalase foi p, lheie is aIso a lalIe p_des_metadata hoIding
lhe DalaIog inlensionaI iuIes lhal have leen nade peisislenl. This is needed lo iecovei
lhe oiiginaI iuIes as lhey veie asseiled (in ils conpiIed DalaIog foin).
If you have peisisled a piedicale foi vhich no lype consliainls has leen given
lefoie, a lype consliainl is deiived, if possilIe, and asseiled. This lype consliainl
ienains even vhen lhe peisislency asseilion is ienoved. If you vanl lo ienove lhis
loo, lhen sulnil a /drop_ic connand. The foIIoving session iIIusliales lhis:

DES> /dbschema
Info: Database '$des'
Info: No tables.
Info: No views.
Info: No integrity constraints.
DES> :-persistent(p(a:int),mysql)
DES> /dbschema
Info: Database '$des'
Info: No tables.
Info: View(s):
* p(a:number(integer))
- Defining SQL statement:
CREATE VIEW p(a) AS
SELECT ALL *
FROM
p_des_table;
Info: No integrity constraints.
DES> /drop_assertion :-persistent(p(a:int),mysql)
DES> /dbschema
Info: Database '$des'
Info: Table(s):
* p(a:number(integer))
Info: No views.
Info: No integrity constraints.
DES> /drop_ic :-type(p(a:int))


Fernando Senz-Prez 125/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> /dbschema
Info: Database '$des'
Info: No tables.
Info: No views.
Info: No integrity constraints.
If you vanl lo conpIeleIy ienove a piedicale, even ils peisislenl
iepiesenlalion, you can use lhe connand /abolish, as in:

DES> /abolish p
DES> /dbschema
Info: Database '$des'
Info: No tables.
Info: No views.
Info: No integrity constraints.
DES> /listing p
Info: 0 rules listed.
DES> /use_db mysql
DES> /dbschema mysql:p
Info: Database 'mysql'
Error: No table or view found with name 'p'.
AIso, diopping lhe SQL viev coiiesponding lo a piedicale ienoves peisislency,
as in:

DES> :-persistent(t(a:int),mysql)
DES> /dbschema
Info: Database '$des'
Info: No tables.
Info: View(s):
* t(a:number(integer))
- Defining SQL statement:
CREATE VIEW t(a) AS
SELECT ALL *
FROM
t_des_table;
Info: No integrity constraints.
DES> drop view t
DES> /dbschema
Info: Database '$des'
Info: No tables.
Info: No views.
Info: No integrity constraints.
%.2.( Sc/ema and Data Visi*ility
The defauIl dalalase (DD) is caIIed $des, and il conlains neladala of each
piedicale foi vhich eilhei a lype asseilion oi an SQL lalIe ciealion slalenenl has leen
issued. If one nakes a piedicale peisislenl in an exleinaI dalalase (LD), ils neladala
as veII as ils dala is visilIe lolh lo DD and LD. The foIIoving session iIIusliales lhis:

DES> /use_db $des
DES> :-persistent(p(a:int),mysql)
DES> /assert p(1)
DES> /show_compilations on


Fernando Senz-Prez 126/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> select * from p
Info: SQL statement compiled to:
answer(A) :-
p(A).
answer(p.a:number(integer)) ->
{
answer(1)
}
Info: 1 tuple computed.
DES> /use_db mysql
DES> select * from p
answer(a:integer(4)) ->
{
answer(1)
}
Info: 1 tuple computed.
Nole lhal in lhe fiisl case (fiisl SELECT alove) vhen lhe cuiienl dalalase is
$des, DLS soIves lhe queiy (in lhis case ieliieving lupIes fion DD), and in lhe
second case (second SELECT alove), lhe queiy is diieclIy sulnilled lo lhe LD, vhich
soIves il. In lhe fiisl, case, lhe SQL slalenenl is conpiIed lo DalaIog and soIved ly lhe
deduclive engine, and in lhe second one, dala and neladala aie coIIecled fion LD
and shovn as a iesuIl. Reliieved lypes fion an exleinaI dalalase diffei in geneiaI lo
lhose nanaged ly DLS, as il can le seen in lhis exanpIe. This is nol an issue as Iong as
equivaIenl lypes aie found (in lhis case, number(integer) is consideied as
equivaIenl lo integer(4), as nuneiic size consliainls aie nol handIed ly DLS, up lo
nov).
As aIieady inlioduced in Seclion 5.1.7, even vhen a conneclion is opened, lheii
dala and neladala aie nol knovn unIess il lecones lhe cuiienl dalalase, as iIIuslialed
nexl:

DES> /use_db mysql
DES> create table q(a int)
DES> insert into q values (2)
Info: 1 tuple inserted.
DES> select * from q
answer(a:integer(4)) ->
{
answer(2)
}
Info: 1 tuple computed.
DES> /use_db $des
DES> select * from q
Error: Unknown table or view "q"
DES> q(X)
Warning: Undeclared predicate(s): [q/1]
{
}
Info: 0 tuples computed.
Hovevei, a peisisled piedicale does have access lo dala and neladala in lhe
LD il vas nade peisislenl. To shov lhis, and foIIoving lhe alove syslen session, Iel's
asseil lhe foIIoving iuIe:


Fernando Senz-Prez 127/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


DES> /assert p(X):-q(X)
Warning: Undefined predicate(s): [q/1]
DES> p(X)
{
}
Info: 0 tuples computed.
DES> :-persistent(p(a:int),mysql)
DES> p(X)
{
p(2)
}
Info: 1 tuple computed.
Heie, lhe exleinaI dalalase is assuned lo hoId a ieIalion q/1 vilh a lupIe q(2)
in ils neaning.
%.2.8 2&&lications
Ieisisling piedicales opens a liand nev scenaiio foi seveiaI ieasons: Iiisl,
piedicales aie no Iongei Iiniled ly avaiIalIe nenoiy, inslead, peisisled piedicales aie
using as nuch secondaiy sloiage as needed and piovided ly lhe undeiIying exleinaI
dalalase. Iiedicale size Iinil is lheiefoie noved lo lhe exleinaI dalalase. Second,
piocessing is diiecled lo lhe exleinaI dalalase foi iuIes lhal can le piojecled, and lo lhe
deduclive engine foi iuIes lhal can nol. This vay, one can lake advanlage of lhe
exleinaI dalalase peifoinance and scaIaliIily. Thiid, queiies vhich aie nol possilIe in
an exleinaI dalalase can le soIved ly lhe deduclive engine. So, one can exlend
exleinaI dalalase expiessiveness vilh lhe added fealuies in DLS. IinaIIy, as seveiaI
ODC conneclions aie aIIoved al a line, diffeienl piedicales can le nade peisislenl in
diffeienl DMSs, vhich aIIovs foi inleiopeialiIily anong exleinaI ieIalionaI engines
and lhe IocaI deduclive engine, lheiefoie enalIing lusiness inleIIigence appIicalions.
Ioi inslance, Iel's considei MySQL, vhich does nol suppoil iecuisive queiies
up lo ils cuiienl veision 5.5. The foIIoving piedicale can le nade peisislenl in lhis
RDMS even vhen il is iecuisive:

DES> :-persistent(path(a:int,b:int),mysql)
DES> /assert path(1,2)
DES> /assert path(2,3)
DES> /assert path(X,Y):-path(X,Z),path(Z,Y)
Warning: Recursive rule cannot be transferred to external
database (kept in local database for its processing):
path(X,Y) :-
path(X,Z),
path(Z,Y).
DES> path(X,Y)
{
path(1,2),
path(1,3),
path(2,3)
}
Info: 3 tuples computed.


Fernando Senz-Prez 128/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Heie, non-iecuisive iuIes aie sloied in lhe exleinaI dalalase vheieas lhe
iecuisive one is kepl in lhe IocaI dalalase. LxleinaI iuIes aie piocessed ly MySQL and
IocaI iuIes ly lhe IocaI deduclive engine.
In addilion, iecaII lhal you can use SQL on lhe cuiienl dalalase schena (foi
vhich lhe peisislenl piedicale schena is knovn). Then, even speciaI SQL fealuies
incIuded in DLS, such as hypolhelicaI queiies, can le used. Ioi exanpIe, and foIIoving
lhe alove syslen session:

DES> assume select 3,1 in path(a,b) select * from path
answer(path.a:number(integer),path.b:number(integer)) ->
{
answer(1,1),
answer(1,2),
answer(1,3),
answer(2,1),
answer(2,2),
answer(2,3),
answer(3,1),
answer(3,2),
answer(3,3)
}
Info: 9 tuples computed.
This exanpIe aIso shovs lhal DLS is alIe lo conpule noie queiies lhan an
RDMS. Ioi inslance, neilhei MS SQL Seivei noi D2 aIIov cycIes in lhe alove palh
definilion. This is nol lhe nosl inpoilanl Iinilalion of iecuision in cuiienl RDMSs,
nole lhal slialified iecuision is nol suppoiled foi noie lhan one slialun. This neans
lhal iecuisive SQL queiies invoIving EXCEPT, NOT IN, aggiegales, ... aie nol aIIoved
in cuiienl RDMSs such as SQL Seivei and D2. Anolhei Iinilalion is Iineai iecuision:
lhe alove iuIes cannol le expiessed in a RDMS's SQL as lheie aie seveiaI iecuisive
caIIs. To nane anolhei, UNION ALL is enfoiced in lhose SQLs, so lhal jusl UNION is nol
aIIoved. Ioi inslance, lhe foIIoving queiy is iejecled in any cuiienl conneiciaI
RDMS, lul accepled ly DLS:

DES> /duplicates on
DES> /multiline on
DES> CREATE TABLE edge(a int, b int);
DES> INSERT INTO edge VALUES(1,2);
Info: 1 tuple inserted.
DES> INSERT INTO edge VALUES(2,3);
Info: 1 tuple inserted.
DES> INSERT INTO edge VALUES(1,3);
Info: 1 tuple inserted.
DES> :-persistent(edge(a:int,b:int),mysql).
DES> :-persistent(path(a:int,b:int),mysql).
DES> WITH RECURSIVE path(a, b) AS
SELECT * FROM edge
UNION -- Discarding duplicates (ALL is not required)
SELECT p1.a,p2.b
FROM path p1, path p2
WHERE p1.b=p2.a
SELECT * FROM path;


Fernando Senz-Prez 12/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Warning: Recursive rule cannot be transferred to external
database (kept in local database for its processing):
path_2_1(A,B) :-
path(A,C),
path(C,B).
answer(path.a:number(integer),path.b:number(integer)) ->
{
answer(1,2),
answer(1,3),
answer(2,3)
}
Info: 3 tuples computed.
Nole lhe diffeience againsl lhe nexl queiy, vhich does nol discaid dupIicales:

DES> WITH RECURSIVE path(a, b) AS
SELECT * FROM edge
UNION ALL -- Keeping duplicates
SELECT p1.a,p2.b
FROM path p1, path p2
WHERE p1.b=p2.a
SELECT * FROM path;
Warning: Recursive rule cannot be transferred to external
database (kept in local database for its processing):
path(A,B) :-
path(A,C),
path(C,B).
answer(path.a:number(integer),path.b:number(integer)) ->
{
answer(1,2),
answer(1,3),
answer(1,3),
answer(2,3)
}
Info: 4 tuples computed.
%.2. Ca0eats
%.2..1 Incom&lete Meanings
If a piedicale p vhich depends on an exleinaI ieIalion r is nade peisislenl,
lhen il nay le lhe case lhal lhe defauIl dalalase engine cannol gel lhe neaning of r
lul via p, as iIIuslialed in lhe foIIoving exanpIe:

DES> /current_db
Info: The current database is '$des'. DBMS: $des
DES> /assert p(1)
DES> /assert p(X):-r(X)
Warning: Undefined predicate(s): [r/1]
DES> :-persistent(p(a:int),access)
DES> p(X)
{
p(1),
p(2),
p(3)


Fernando Senz-Prez 13!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

}
Info: 3 tuples computed.
DES> r(X)
{
}
Info: 0 tuples computed.
DES> /use_db access
DES> /current_db
Info: The current database is 'access'. DBMS: access
DES> r(X)
{
r(2),
r(3)
}
Info: 2 tuples computed.
%.2..2 =&ening and Closing Connections
Lach line a peisislenl asseilion is issued ovei a given conneclion, lhis
conneclion is opened, aIlhough lhe cuiienl dalalase is nol changed lo il. In addilion,
ils is nol cIosed aIlhough a /drop_assertion connand vas issued.
A conneclion cannol le cIosed if any peisislenl piedicale ienains on il.
%.2..3 2*olis/ing ?redicates
The connand /abolish nol onIy aloIishes iuIes in lhe deduclive dalalase lul
aIso lhose piedicales lhal have leen peisislenl in lhe exleinaI dalalase, diopping lheii
lalIe and viev definilions.
%.2..4 1ull Values
Iiocessing of nuII vaIues invoIving LD and LD is nol sliII suppoiled as lhey
have diffeienl iepiesenlalions. So, oulei joins aie nol suppoiled up lo nov.
%.2..% E)ternal Data*ase ?rocessing
OnIy lhe liansfeiied iuIes of peisisled piedicales can le piocessed ly lhe LD.
In pailicuIai, neilhei DalaIog queiies noi SQL queiies sulnilled fion $des aie
liansIaled inlo exleinaI SQL and lheiefoie piocessed ly such LD. OnIy SQL queiies
in lhe sane conneclion as lhe peisisled piedicale aie piocessed ly lhe LD. Hovevei,
fuluie ieIeases nighl liansIale queiies sulnilled fion $des.
%.2.." Su&&orted ?lat:orms
A Iiniled nunlei of syslens have leen lesled, incIuding MySQL, MS Access,
IM D2, and olheis. Hovevei, lesl suiles aie ialhei snaII up lo nov. IIease iepoil
any fauIl foi youi appIicalion in oidei lo le fixed.
%.3 Sa:ety and Com&uta*ility
%.3.1 Classical Sa:ety
uiIl-in piedicales aie appeaIing, lul lhey cone al a cosl, vhich vas aIieady
noliced in Seclion 4.5. The donain of lheii aigunenls is infinile, in conliasl lo lhe finile
donains of each aigunenl of any usei-defined piedicale. Since il is neilhei ieasonalIe
noi possilIe lo (exlensionaIIy) give an infinile ansvei, vhen a sulgoaI invoIving a


Fernando Senz-Prez 131/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

luiIl-in is going lo le conpuled, ils aigunenls need lo le iange iesliicled, i.e., lhe
aigunenls have lo lake vaIues piovided ly olhei sulgoaIs. To iIIusliale lhis poinl,
considei sulnilling lhe foIIoving viev lo lhe piogian fiIe relop.dl:

less(X,Y) :- X < Y, c(X,Y).
Since lhe goaI is less(X,Y), and lhe conpulalion is Iefl lo iighl, lolh X and Y
aie nol iange iesliicled vhen conpuling lhe goaI X < Y and, lheiefoie, lhis goaI
ianges ovei lvo infinile donains: lhe one foi X and lhe one foi Y. We do nol aIIov lhe
conpulalion of such iuIes. Hovevei, if ve ieoidei lhe lvo goaIs as foIIovs:

less(X,Y) :- c(X,Y), X < Y.
ve gel lhe expecled iesuIl:
{
less(a1, b2),
less(a2, b2)
}
Nole, lhen, lhal luiIl-in piedicales affecl decIaialive senanlics, i.e., lhe
inlended neaning of lhe lvo foinei vievs shouId le lhe sane, aIlhough acluaIIy il is
nol. DecIaialive senanlics is lheiefoie affecled ly lhe undeiIying opeialionaI
nechanisn. Nolice, nonelheIess, lhal DalaIog is Iess sensilive lo opeialionaI issues
lhan IioIog and il couId le said lo le noie decIaialive. Iiisl, lecause of leininaling
issues as aIieady inlioduced, and second, lecause lhe piolIenalic fiisl viev can le
aulonalicaIIy liansfoined inlo lhe second, conpulalion-safe, one, as ve expIain nexl.
We can check vhelhei a iuIe is safe in lhe sense lhal aII ils vaiialIes aie iange
iesliicled and, lhen, ieoidei lhe goaIs foi aIIoving ils conpulalion. Iiisl, ve need a
nolion of safely, vhich inluiliveIy seens cIeai lul lhal acluaIIy is undecidalIe
|ZCI+97j. Sone sinpIe sufficienl condilions foi lhe safely of DalaIog piogians can le
inposed, vhich neans lhal iuIes oleying lhese condilions can le safeIy conpuled,
aIlhough lheie aie iuIes lhal, even vioIaling sone condilions, can le acluaIIy
conpuled. We inpose lhe foIIoving (veak) condilions |UIIn95, ZCI+97j foi safe iuIes
adapled lo oui conlexl:
1. Any vaiialIe ( in a iuIe r is safe if:
a. ( occuis in sone posilive goaI iefeiiing lo a usei-defined piedicale
l. r conlains sone equaIily goaI (=), vheie ) is safe () can le a conslanl,
vhich, olviousIy, nakes ( safe)
c. A vaiialIe ( in lhe goaI ( is #'pression is safe vhenevei aII vaiialIes in
#'pression aie safe
2. A iuIe is safe if aII ils vaiialIes aie safe.
Nolice lhal lhese condilions, cuiienlIy suppoiled ly lhe syslen, aie veak since
lhey assune lhal usei-defined piedicales aie safe, vhich is nol aIvays lhe case (lul
onIy iequiie anaIysing IocaIIy each iuIe foi deciding veak safely). To nake lhese
condilions sliongei, 1.a. has lo le changed lo: ( occuis in sone posilive goaI iefeiiing
lo a safe usei-defined piedicale, and add 3. A piedicale is safe if aII of ils vaiialIes aie
safe. The changed condilions vouId iequiie a gIolaI anaIysis of lhe piogian, vhich is
nol suppoiled ly DLS up lo nov.


Fernando Senz-Prez 132/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The luiIl-in piedicale is has lhe sane piolIen as conpaiison opeialois as
veII, lul il onIy denands giound ils second aigunenl (cf. condilion 1.c alove).
Negalion iequiies ils aigunenl lo have no unsafe vaiialIes. In addilion, lo le coiieclIy
conpuled, lhe iesliiclions in lhe donains of lhe safe vaiialIes il nay conlain shouId le
conpuled lefoie. The ieadei is iefeiied lo Seclion 3.6 in |UIIn95j foi finding lhe
piolIens vhen inleipieling iuIes vilh negalion.
DLS piovides a check lhal aIIovs deciding if a iuIe is safe and, if so, il foIIovs a
piogian liansfoinalion foi ieoideiing ils goaIs in oidei lo nake il conpulalIe in a
Iefl-lo-iighl oidei. This liansfoinalion does nol cone ly defauIl, and il can le changed
vilh lhe connand /safe Switch, vheie Switch can lake lvo vaIues: on, foi
enalIing piogian liansfoinalion, and off, foi disalIing lhis liansfoinalion. If
Switch is nol incIuded, lhen lhe connand infoins vhelhei piogian liansfoinalion
is enalIed oi disalIed.
The anaIysis peifoined ly lhe syslen al conpiIe-line vains aloul safely and
conpulaliIily as foIIovs:
1. Raise an eiioi if:
a. A goaI invoIving a conpaiison opeialoi will le non-giound al iun-line.
l. The expiession E in a goaI X is E will le non-giound al iun-line.
c. The goaI not(G) conlains unsafe vaiialIes oi ils safe vaiialIes aie nol
iesliicled so fai.
2. Raise a vaining if:
a. A goaI invoIving a conpaiison opeialoi may le non-giound al iun-line.
l. The expiession E in a goaI X is E may le non-giound al iun-line.
This anaIysis is peifoined in seveiaI cases:
Whenevei a iuIe is asseiled (eilhei nanuaIIy vilh lhe connand /assert oi
aulonalicaIIy vhen consuIling piogians). A iuIe is aIvays asseiled, even
vhen il is delecled as unsafe oi il nay iaise an exceplion al iun-line. RecaII
lhal safely is undecidalIe and lheie aie iuIes delecled as unsafe lhal can le
acluaIIy and coiieclIy conpuled.
When a queiy, conjunclive queiy (auloviev) oi viev is sulnilled. They aie
iejecled and nol conpuled if unsafely oi unconpulaliIily is delecled and
cannol le iepaiied (lecause piogian liansfoinalion is disalIed oi lheie is no
vay). Nolice lhal lheie can le unsafe oi unconpulalIe iuIes aIieady consuIled
lhan can yieId an incoiiecl iesuIl oi iaise a iun-line exceplion.
ConcIuding, one can expecl a coiiecl ansvei vhenevei no unsafe,
unconpulalIe iuIe has leen asseiled lo an enply dalalase. RecaII lhal lhe IocaI
anaIysis ieIies on lhe veak condilion lhal assunes lhal lhe consuIled iuIes aie safe.
Nexl, an exanpIe of unsafe iuIe incIuding negalion is piovided. As inlioduced,
such a iuIe, vhen asseiled, iaises an eiioi, lul il is asseiled in any case in oidei lo
shov ils nislehavioui.

DES> /assert q(0)
DES> /assert p(X):-not(q(X))


Fernando Senz-Prez 133/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Error: not(q(X)) might not be correctly computed because of the
unrestricted variable(s):
[X]
Warning: This rule is unsafe because of variable(s):
[X]
DES> p(X)
{
}
Info: 0 tuples computed.
As lhe donain of X in p(X) is nol iange iesliicled, no lupIes aie found in lhe
Iefl-lo-iighl lop-dovn seaich. If ve sulnil a queiy as p(1), lhe negalion not(q(1))
should le pioven:

DES> p(1)
{
}
Info: 0 tuples computed.
Hovevei, as iIIuslialed, lheie is no lupIes in lhe ansvei foi such a queiy. The
nislehavioui of lhe iuIe foi p/1 eneiges heie due lo lhe vay ansveis aie conpuled
via an exlension lalIe. As fai as lhe queiy p(1) is sulsuned ly a pievious caII (p(X)),
iesuIls in lhe exlension lalIe aie ieused. ul if lhe exlension lalIe is cIeaied, lhen p(1)
can le pioved:

DES> /clear_et
DES> p(1)
{
p(1)
}
Info: 1 tuple computed.
Nolice lhal lolh caIIs can occui duiing a conpulalion, disalIing lhe
oppoilunily lo cIeai lhe exlension lalIe, as in:

DES> p(X),p(1)
Info: Processing:
answer(X) :-
p(X),
p(1).
{
}
Info: 0 tuples computed.
A siniIai silualion happens vilh equaIily:

DES> p(X),X=1
Info: Processing:
answer(X) :-
p(X),
X = 1.
{
}
Info: 0 tuples computed.


Fernando Senz-Prez 134/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

AIso nolice lhal, if sinpIificalion node is enalIed vilh lhe connand
/simplification on, lhen lhis conjunclive queiy is sinpIified and conpuled as
foIIovs:

DES> p(X),X=1
Info: Processing:
answer(1) :-
p(1).
{
answer(1)
}
Info: 1 tuple computed.
%.3.2 Sa:ety :or 2ggregates and Du&licate Elimination
Anolhei souice of unsafely, depailing fion lhe cIassicaI nolion, iesides in
nelapiedicales as distinct/2 and aggiegales. A set variable is any vaiialIe occuiiing
in a nelapiedicale such lhal il is nol lound ly lhe nelapiedicale. Ioi inslance, Y in lhe
goaI distinct([X],t(X,Y)) is a sel vaiialIe, as veII as in
group_by(t(X,Y),[X],C=count).
ecause conpuling a goaI foIIovs SLD oidei, if a sel vaiialIe is used aflei lhe
nelapiedicale, as in distinct([X],t(X,Y)), p(Y), lhen lhis is an unsafe goaI as
in lhe caII lo distinct, vaiialIe Y is nol lound, and aII lupIes in t/2 aie consideied
foi conpuling ils oulcone. Svapping lolh sulgoaIs yieIds a safe goaI. So, dala
piovideis foi sel vaiialIes aie onIy aIIoved lefoie lheii use in such nelapiedicales.
AIong conpiIalions, unsafe iuIes can le aulonalicaIIy geneialed, as in lhe
liansIalions of oulei joins. Hovevei, lhey aie safe lecause of lheii use: unsafe
aigunenls of such iuIes aie aIvays given as inpul in goaIs. So, node infoinalion foi
piedicales is handIed lhioughoul piogian conpiIalions lo delecl liuIy unsafe iuIes,
avoiding lo iaise vainings aloul syslen geneialed iuIes. Nolice, hovevei, lhal you
can sliII nanuaIIy viile an unsafe caII lo lhese syslen-geneialed piedicales, yieIding lo
incoiiecl iesuIls, as lhe foIIoving exanpIes iIIusliales:

DES> /assert t(1)
DES> /assert s(2)
DES> /assert l(X):-lj(t(X),s(Y),X=Y)
DES> /development on
DES> /listing
'$p0'(X,Y) :-
'$p1'(X,Y).
'$p0'(X,'$NULL'(A)) :-
t(X),
not('$p1'(X,Y)).
'$p1'(X,Y) :-
X = Y,
t(X),
s(Y).
l(X) :-
lj('$p0'(X,Y)).
s(2).
t(1).
Info: 6 rules listed.


Fernando Senz-Prez 135/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> '$p0'(X,Y)
{
'$p0'(1,'$NULL'(0))
}
Info: 1 tuple computed.
DES> /list_et
Answers:
{
not('$p1'(1,A)),
t(1),
'$p0'(1,'$NULL'(0))
}
Info: 3 tuples in the answer table.
Calls:
{
'$p0'(A,B)
}
Info: 1 tuple in the call table.
Lxlension lalIe conlains lhe non-giound enliy not('$p1'(1,A)), vhich is
nol safe.
%.4 Modes :or Unsa:e ?redicates
Modes in IioIog aie used lo decIaie piopeilies of piedicales al caII and/oi exil
lines. Heie, ve loiiov nodes lo specify e'pected piopeilies foi a piedicale in oidei lo
le coiieclIy conpuled. We use node i (foi an inpul aigunenl) and o (foi an oulpul
aigunenl) in a diffeienl vay as in IioIog slandaid (vhich, indeed does nol incIude
lhese synloIs) so lhal i neans lhal lhe aigunenl is expecled lo le giound al caII line,
and 'o' neans lhal il is nol, lhough il nighl le. Wheieas in safe DalaIog, aII nodes
shouId le o , in DLS ve can find i nodes as veII lecause unsafe piedicales aie
aIIoved. Ioi inslance, lecause lheie aie infinile luiIl-ins as conpaiison opeialois (<, >,
...), il is inleiesling lo aIIov i nodes as veII, as in lhe nexl exanpIe, lhal is inlended lo
conpule lhe fiisl T naluiaI nunleis:

nat(T,1).
nat(T,X) :- nat(T,Y),X=Y+1,X<T.
Lxpecled goaIs nusl have a giound fiisl aigunenl, as:

nat(100,X)
vhich ieluins lhe fiisl 1OO naluiaIs. Olheivise, a iun-line exceplion is iaised:

DES> nat(X,Y)
Exception: Non ground argument(s) found in goal 1<T in the
instanced rule:
nat(T,X) :-
nat(T,1),
1<T,
X=1+1.
Asserted at 10:23:37 on 7-28-2013.


Fernando Senz-Prez 136/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

So, each line a iuIe is asseiled, il is checked foi cIassicaI safely and, if nol safe, a
node asseilion is sloied, indicaling lhe inpul iequiienenl of offending aigunenls.
The asseilion has lhe foIIoving synlax:

:-mode(ModeSchema)

ModeSchema ::= PredName(Mode,...,Mode)

Mode ::= i % The argument must be ground at call time
Mode ::= o % The argument can be a free variable at call time
In lhe exanpIe alove, lhe aulonalicaIIy-sloied asseilion is:

:-mode(nat(i,o)).
This can Iisled vilh lhe connand /list_modes, vhich Iisls aII asseiled
nodes, and /list_modes N/A foi a give piedicale of nane N and aiily A.
Theiefoie, such decIaialions aie undeislood noie fion a docunenlalion poinl-
of-viev lhan fion consliainls (as lypes, iefeienliaI inlegiily consliainls, ...), as node
asseilions iecaII useis aloul expecled piopeilies foi lhe queiies (in addilion lo lhe fiisl
nessage lhey gol vhen conpiIing an unsafe iuIe). If no node is asseiled foi a given
piedicale, il is cIassicaI-safe.
AIlhough lhe usei can onIy exanine piedicale nodes, lhe syslen keeps liack of
nodes al iuIe-IeveI. Lach line a iuIe is asseiled oi ieliacled, lhe nodes foi ils piedicale
aie updaled vilh lhe aIieady sloied nodes foi lhe iesl of lhe piedicale iuIes, if any.
%.% SourceGtoGSource Arans:ormations
CuiienlIy, lvo souice-lo-souice liansfoinalions aie possilIe undei denand:
Iiisl, as expIained in lhe pievious seclion, vhen safely liansfoinalions aie enalIed via
lhe connand /safe on, iuIe lodies aie ieoideied lo liy lo pioduce a safe iuIe.
Second, vhen sinpIificalion is enalIed via lhe connand /simplification on, iuIe
lodies conlaining equaIilies, true, and not(BooleanValue) aie sinpIified.
In addilion, lheie is aIso pIace foi seveiaI aulonalic liansfoinalions (cf. Seclion
5.7 lo knov hov lo dispIay such liansfoinalions):
A cIause conlaining a disjunclive lody is liansfoined inlo a sels of cIauses
vilh conjunclive lodies.
A cIause conlaining an oulei join piedicale is liansfoined inlo an
execulalIe foin.
A cIause conlaining an aggiegale piedicale is liansfoined inlo an
execulalIe foin incIuding giouping ciileiion.
A cIause conlaining lhe goaI not(is_null(+Term)) is liansfoined inlo a
cIause vilh lhis goaI iepIaced ly is_not_null(+Term).
%." MultiGline Mode
y defauIl, DLS connand pionpl ieads singIe-Iine inpuls and, lheiefoie,
ending leininalion chaiaclei is oplionaI (as lhe dol (.) in DalaIog and lhe senicoIon
(;) in SQL and RA). ul, vhen viiling a Iong queiy, as usuaI in SQL, lieaking dovn


Fernando Senz-Prez 137/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

lhe senlence aIong seveiaI Iines enhances ieadaliIily. This is aIso possilIe in DLS ly
enalIing nuIli-Iine node vilh lhe connand /multiline on. Hovevei, in lhis
scenaiio, lhe leininaling chaiaclei nusl le issued in oidei lo knov vhen lo finish
paising lhe inpul queiy. Reluining lo singIe-Iine node is jusl ly issuing /multiline
off.
Wilh nuIli-Iine inpul, nuIli-Iine ienaiks (encIosed lelveen /* and */) aie
aIso aIIoved. Nole lhal nesled ienaiks aie suppoiled, loo, as:

/*
First remark
/*
Second, nested remark
*/
*/
%.( De0elo&ment Mode
This seclion is focused al lhose inleiesled in nodifying and exlending lhe
syslen. So, fion a syslen inpIenenloi vievpoinl, il is handy lo shov seveiaI
inpIenenlalion-specific issues such as souice-lo-souice liansfoinalions and inleinaI
iepiesenlalion of nuII vaIues. To lhis end, lhe connand /development |on|offj
has leen nade avaiIalIe. Lels considei lhe foIIoving syslen session:

DES> /development off
DES> /assert p(X):-X=1;X=2
DES> /assert c(C):-count(p(X),X,C)
DES> /assert q(1)
DES> /assert l(X,Y):-lj(p(X),q(Y),X=Y)
DES> /listing

c(C) :-
count(p(X),X,C).
l(X,Y) :-
lj(p(X),q(Y),X = Y).
p(X) :-
X = 1
;
X = 2.
q(1).

Info: 4 rules listed.

DES> l(X,Y)
{
l(1,1),
l(2,null)
}
Info: 2 tuples computed.

Nexl, ve enalIe lhe deveIopnenl node foi Iislings:

DES> /development on


Fernando Senz-Prez 138/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> l(X,Y)

{
l(1,1),
l(2,'$NULL'(59))
}
Info: 2 tuples computed.
Heie, lhe inleinaI iepiesenlalion of nuIIs is avaiIalIe. If ve iequesl lhe Iisling of
lhe sloied iuIes in deveIopnenl node:

DES> /listing

'$p0'(A,'$NULL'(B)) :-
p(A),
not('$p1'(A,C)).
'$p0'(A,B) :-
'$p1'(A,B).
'$p1'(A,B) :-
p(A),
q(B),
A = B.
c(C) :-
count(p(X),X,'[]',C).
l(X,Y) :-
'$p0'(X,Y).
p(X) :-
X = 2.
p(X) :-
X = 1.
q(1).

Info: 8 rules listed.
Heie, ve see seveiaI souice-lo-souice liansfoinalions: Iiisl, lhe Iefl join, lhen
lhe aggiegale counl, and finaIIy lhe disjunclive iuIe.
DeveIopnenl Iislings aIso aIIovs lo inspecl lhe exlension lalIe Iooking al
(iepealed) facls invoIving nuIIs, as foIIovs:

DES> /assert q(null)
DES> /assert q(null)
DES> q(X)

{
q(1),
q(3),
q('$NULL'(64)),
q('$NULL'(67))
}
Info: 4 tuples computed.
Conpaie lhis lo lhe non-deveIopnenl node:

DES> /development off
DES> q(X)


Fernando Senz-Prez 13/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

{
q(1),
q(3),
q(null)
}
Info: 3 tuples computed.
AIso, one can le avaie fion vheie nuIIs cone lecause of lheii IDs, as in:

DES> /assert p(null)
DES> /listing p

p('$NULL'(70)).
p(X) :-
X = 1.
p(X) :-
X = 2.

Info: 3 rules listed.

DES> l(X,Y)
{
l(1,1),
l(2,'$NULL'(72)),
l('$NULL'(70),'$NULL'(74))
}
Info: 3 tuples computed.
Olseive alove ID 7O. Theie, lhe dala souice iuIe pioviding such an enliy in lhe
ansvei is lhe fiisl iuIe of p.
As SQL slalenenls and RA expiessions aie conpiIed lo DalaIog piogians, lhe
connand /show_compilations on enalIes lhe dispIay of conpiIalions each line
an SQL slalenenl is sulnilled, as lhe foIIoving exanpIe iIIusliales:

DES> /show_compilations on
DES> create table t(a int, b int)
DES> create table s(a int, b int)
DES> select * from t where a>1 union select * from s where b<2
Info: SQL statement compiled to:
answer(A,B) :-
distinct(answer_2_1(A,B)).
answer_2_1(A,B) :-
t(A,B),
A > 1.
answer_2_1(A,B) :-
s(A,B),
B < 2.
answer(t.a, t.b) ->
{
}
Info: 0 tuples computed.


Fernando Senz-Prez 14!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

%.8 Datalog and S#$ Aracers
In conliasl lo inpeialive piogianning Ianguages, deduclive and ieIalionaI
dalalase queiy Ianguages fealuie soIving pioceduies vhich aie fai fion lhe queiy
Ianguages ilseIf. WhiIsl one can liace an inpeialive piogian ly foIIoving each
slalenenl as il is execuled, aIong vilh lhe piogian slale, lhis is nol feasilIe in
decIaialive (high alsliaclion) Ianguages as DalaIog and SQL. Hovevei, lhis does nol
appIy lo IioIog, aIso acknovIedged as a decIaialive Ianguage, lecause one can foIIov
lhe execulion of a goaI via lhe SLD iesoIulion liee and use lhe foui-poil delugging
appioach.
DalaIog slens fion Iogic piogianning and IioIog in pailicuIai, and il can le
aIso undeislood as a sulsel of IioIog. Hovevei, ils opeialionaI lehavioui is quile
diffeienl, since lhe oulcone of a queiy iepiesenls aII lhe possilIe iesoIulions, inslead of
a singIe one as in IioIog. In addilion, lalIing (cf. Seclion 5.5) and piogian
liansfoinalions (due lo oulei joins, aggiegales, sinpIificalions, disjunclions, ...) nake
liacing cunleisone.
SiniIaiIy, SQL iepiesenls a liue decIaialive Ianguage vhich is even failhesl
fion ils conpulalion pioceduie lhan IioIog. Indeed, lhe execulion pIan foi a queiy
incIude liansfoinalions consideiing dala slalislics lo enhance peifoinance. These
queiy pIans aie conposed of piinilive ieIalionaI opeialions (such as Cailesian
pioducl) and speciaIized opeialions foi vhich efficienl aIgoiilhns have leen
deveIoped, conlaining in geneiaI iefeiences lo index usage.
Theiefoie, inslead of foIIoving a noie inpeialive appioach lo liacing, heie ve
focus on a (nave) decIaialive appioach vhich onIy lake inlo accounl lhe oulcones al
sone piogian poinls. This vay, lhe usei can inspecl each poinl and decide vhelhei
ils oulcone is coiiecl oi nol. This appioach viII aIIov lo exanine lhe synlaclicaI giaph
of a queiy, vhich possilIy depends on olhei vievs oi piedicales (SQL oi DalaIog,
iesp.) This giaph nay le cycIic vhen iecuisive vievs oi piedicales aie invoIved.
Hovevei, a given node in lhe giaph viII le liaveised onIy once. In lhe case of DalaIog
queiies, lhis giaph conlains lhe nodes and edges in lhe dependency giaph iesliicled lo
lhe queiy, ignoiing olhei nodes vhich do nol lake pail in ils conpulalion. In lhe case
of SQL, lhe giaph shovs lhe dependencies lelveen a viev and ils dala souices (in lhe
FROM cIause).
Nexl, liacing foi lolh DalaIog queiies and SQL vievs aie expIained and
iIIuslialed vilh exanpIes.
%.8.1 Aracing Datalog #ueries
The connand /trace_datalog Goal [Order] aIIovs lo liace a DalaIog
goaI in lhe given oidei (postorder oi lhe defauIl preorder). CoaIs shouId le lasic,
i.e., no conjunclive oi disjunclive goaIs aie aIIoved. Ioi inslance, Iel's considei lhe
piogian in lhe fiIe negation.dl and ils dependency giaph, shovn in Iiguie 3. A
liacing session couId le as foIIovs:

DES> /c negation
Warning: Undefined predicate(s): [d/0]
DES> /trace_datalog a
Info: Tracing predicate 'a'.
{


Fernando Senz-Prez 141/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

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.
%.8.2 Aracing S#$ Vie3s
Tiacing SQL vievs is siniIai lo liacing DalaIog queiies, lul, inslead of posing a
goaI (invoIving in geneiaI vaiialIes and conslanls) lo liace, onIy lhe nane of a viev
shouId le given. Ioi exanpIe, Iel's considei lhe fiIe family.sql, vhich conlains viev
definilions foi ancestor and parent, vheie lalIes father and mother aie
invoIved in lhe Iallei viev. Nole lhal lhis viev is iecuisive since il depends on ilseIf:

create view parent(parent,child) as
select * from father
union
select * from mother;

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;

Then, liacing lhe viev ancestor is as foIIovs:

DES-SQL> /trace_sql ancestor
Info: Tracing view 'ancestor'.
{
ancestor(amy,carolIII),
...
ancestor(tony,carolIII)
}
Info: 16 tuples in the answer table.
Info : Remaining views: [parent/2,father/2,mother/2]


Fernando Senz-Prez 142/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Input: Continue? (y/n) [y]:
Info: Tracing view 'parent'.
{
parent(amy,fred),
...
parent(tony,carolII)
}
Info: 8 tuples in the answer table.
Info : Remaining views: [father/2,mother/2]
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]:
Info: Tracing view 'mother'.
{
mother(amy,fred),
...
mother(grace,amy)
}
Info: 4 tuples in the answer table.
Info: No more views to trace.
DES-SQL> /trace_datalog father(X,Y)
Info: Tracing predicate 'father'.
{
father(fred,carolIII),
...
father(tony,carolII)
}
Info: 4 tuples in the answer table.
Info: No more predicates to trace.
%. Datalog Declarati0e De*ugger
Oui appioach |CCSO7j lo delug DalaIog piogians is anchoied lo lhe senanlic
IeveI inslead of lhe conpulalion IeveI. We have inpIenenled a noveI vay of appIying
decIaialive delugging, aIso caIIed aIgoiilhnic delugging (a lein fiisl coined in lhe
Iogic piogianning fieId ly L.H. Shapiio |Shap83j) lo DalaIog piogians. Wilh lhis
appioach, il is possilIe lo delug queiies and diagnose nissing ansveis (an expecled
lupIe is nol conpuled) as veII as viong ansveis (a given conpuled lupIe shouId nol
le conpuled). Oui syslen uses a queslion-ansveiing pioceduie vhich slails vhen lhe
usei delecls an unexpecled ansvei foi sone queiy. Then, if possilIe, il poinls lo lhe
piogian fiagnenl iesponsilIe of lhe incoiieclness.
The delugging piocess consisls of lvo phases. Duiing lhe fiisl phase lhe
deluggei luiIds a conpulalion giaph (CC) foi lhe iniliaI queiy Q v.i.l. lhe piogian I.
This giaph iepiesenls hov lhe neaning of lhe iniliaI queiy is consliucled fion aII lhe
caIIs nade aIong ils conpulalion. These caIIs coiiespond lo lhe IileiaIs in lhe iuIe


Fernando Senz-Prez 143/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

lodies used in such conpulalion, vhich in geneiaI leIong lo nany piedicales. Lach
node in lhe giaph is conposed of a IileiaI and ils neaning (i.e., a sel of facls). See noie
delaiIs in |CCSO7j. The second phase consisls of liaveising lhe CC lo find eilhei a
luggy veilex oi a sel of ieIaled incoiiecl veilices. The veilex associaled lo lhe iniliaI
queiy Q is naiked aulonalicaIIy as non-vaIid ly lhe deluggei. The iesl of lhe veilices
aie naiked iniliaIIy as unknovn. In oidei lo nininize lhe nunlei of queslions asked
ly a decIaialive deluggei, seveiaI liaveising slialegies have leen sludied
|CalaO5,SiIvO7j. Hovevei, lhese slialegies aie onIy adequale foi decIaialive deluggeis
lased on liees and nol on giaphs. The cuiienlIy inpIenenled slialegy aIieady conlains
sone ideas of hov lo nininize lhe nunlei of queslions in a CC:
Iiisl, lhe deluggei asks aloul lhe vaIidily of veilices lhal aie nol pail of cycIes in
oidei lo find a luggy veilex, if il exisls. OnIy vhen lhis is no Iongei possilIe, lhe
veilices lhal aie pail of cycIes aie visiled.
Lach line lhe usei indicales lhal a veilex (Queiy = IaclSel) is vaIid, i.e., lhe vaIidily
of lhe ansvei foi lhe sulqueiy Queiy is ensuied, lhe looI changes lo vaIid aII lhe
veilices vilh queiies sulsuned ly Queiy.
Lach line lhe usei indicales lhal a veilex (Queiy = IaclSel) is non-vaIid, lhe looI
changes lo non-vaIid aII lhe veilices vilh queiies sulsuned ly Queiy.
The Iasl lvo ilens heIp lo ieduce lhe nunlei of queslions, deducing
aulonalicaIIy lhe vaIidily of sone veilices fion lhe vaIidily of olheis.
As an exanpIe, ve shov a deluggei session foi lhe queiy br_is_even in lhe
piogian parity.dl, vhich has leen changed lo conlain an eiioi in lhe foIIoving
iuIe:

has_preceding(X) : br(X), br(Y), Y>X. %error: Y>X should be Y<X
In lhis case, lhe usei expecls lhe ansvei foi lhe queiy br_is_even lo le
{br_is_even}, lecause lhe ieIalion br conlains lvo eIenenls: a and b. Hovevei, lhe
ansvei ieluined ly lhe syslen is {}, vhich neans lhal lhe coiiesponding queiy vas
unsuccessfuI.
The avaiIalIe connand foi slailing a delugging session is /debug_datalog
Goal, vheie Goal is a lasic goaI, i.e., no conjunclive oi disjunclive goaIs aie aIIoved.
Theiefoie, lhe usei can slail a lypicaI delugging session as foIIovs:

DES> /debug_datalog br_is_even

Is br(a) = {br(a)} valid(v)/nonvalid(n)/abort(a) [v]? v
Is has_preceding(a) = {has_preceding(a)}
valid(v)/nonvalid(n)/abort(a) [v]? n
Is br(E) = {br(a),br(b)} valid(v)/nonvalid(n)/abort(a) [v]?

Error in relation: has_preceding/1
Witness query : has_preceding(a) -> {has_preceding(a)}

More information? (yes(y)/no(n)/abort(a)) [n]? y

Is the witness query a wrong answer(w)/missing
answer(m)/abort(a) [w]? w



Fernando Senz-Prez 144/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Error in relation: has_preceding/1
Error in rule :
has_preceding(X) :-
br(X),
br(Y),
Y > X.
File :
c:/fernan/research/bddeduc/des/releases/des3.0/des3.0windows32si
cstus/des/examples/parity.dl
Lines: 18,19
In lhis pailicuIai case, onIy lhiee queslions aie necessaiy lo find oul lhal lhe
ieIalion has_preceding is incoiieclIy defined. In addilion, ly iequesling foi noie
infoinalion, ve can even find oul lhe offending iuIe in lhe piedicale.
The conpIele synlax of lhe connand is:

/debug_datalog Goal [Level]

vhich slails lhe deluggei foi lhe lasic goaI Goal al piedicale oi cIause IeveI. LeveI is
indicaled vilh lhe oplions p and c foi Level, iespecliveIy. DefauIl is p.
%.1' S#$ Declarati0e De*ugger
As in lhe pievious seclion, heie ve focus on a decIaialive appioach lo
delugging, foIIoving |CCS12aj (foinei veision of lhe deluggei is lased on |CCS11lj
and sulsuned ly lhe cuiienl one, vhich is a liand nev inpIenenlalion). Theie,
possilIe eiioneous oljecls coiiespond lo vievs, and lhe deluggei Iooks foi eiioneous
vievs asking lhe usei vhelhei lhe iesuIl of a given viev is as expecled.
When lhe usei slails lhe deluggei foi a viev vilh lhe connand /debug_sql
View, lhe deluggei luiIds inleinaIIy ils conpulalion liee and slails lhe delugging
session. The iool of lhe liee is lhe viev undei delugging, ils nodes can le eilhei vievs
oi lalIes, and chiIdien of a viev aie aII of lhe vievs and lalIes occuiiing in lhal viev
(lalIe nodes do nol have chiIdien). This liee is liaveised and lhe vaIidily (vhelhei lhe
viev oulcone nalches ils inlended neaning) of each node is asked lo lhe usei. If a
given node is checked as vaIid, ils sulliee is assuned lo le vaIid and il is no Iongei
liaveised. Olheivise, lhe node ilseIf oi one of ils descendanls is assuned lo le
nonvaIid. In lhis case, lhe sulliee is liaveised lo find lhe eiioneous node.
Consideiing lhe fiIe pets1.sql in lhe diiecloiy examples/SQLDebugger
(lhe piolIen is expIained in lhe sane fiIe), ve find lhal lhe viev Guest ieluins an
unexpecled ansvei:

DES> /process examples/SQLDebugger/pets1.sql
...
DES> select * from Guest;

answer(Guest.id:number(integer),Guest.name:string(varchar(50)))
->
{
answer(1,'Mark Costas'),
answer(2,'Helen Kaye'),
answer(3,'Robin Scott')


Fernando Senz-Prez 145/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

}
Info: 3 tuples computed.
In facl, onIy Robin Scott is expecled in lhe iesuIl sel. Then, ve can delug
lhal viev as foIIovs:

DES> /debug_sql Guest
Info: Debugging view 'Guest'.
{
1 - 'Guest'(1,'Mark Costas'),
2 - 'Guest'(2,'Helen Kaye'),
3 - 'Guest'(3,'Robin Scott')
}
Input: Is this the expected answer for view 'Guest'?
(y/n/m/mT/w/wN/a/h) [n]: n
Info: Debugging view 'CatsAndDogsOwner'.
{
1 - 'CatsAndDogsOwner'(1,'Wilma'),
2 - 'CatsAndDogsOwner'(2,'Lucky'),
3 - 'CatsAndDogsOwner'(3,'Rocky')
}
Input: Is this the expected answer for view 'CatsAndDogsOwner'?
(y/n/m/mT/w/wN/a/h) [y]: n
Info: Debugging view 'NoCommonName'.
{
1 - 'NoCommonName'(1),
2 - 'NoCommonName'(2),
3 - 'NoCommonName'(3)
}
Input: Is this the expected answer for view 'NoCommonName'?
(y/n/m/mT/w/wN/a/h) [y]: n
Info: Debugging view 'LessThan6'.
{
1 - 'LessThan6'(1),
2 - 'LessThan6'(2),
3 - 'LessThan6'(3),
4 - 'LessThan6'(4)
}
Input: Is this the expected answer for view 'LessThan6'?
(y/n/m/mT/w/wN/a/h) [y]: y
Info: Debugging view 'AnimalOwner'.
{
1 - 'AnimalOwner'(1,'Kitty',cat),
2 - 'AnimalOwner'(1,'Wilma',dog),
3 - 'AnimalOwner'(2,'Lucky',dog),
4 - 'AnimalOwner'(2,'Wilma',cat),
5 - 'AnimalOwner'(3,'Oreo',cat),
6 - 'AnimalOwner'(3,'Rocky',dog),
7 - 'AnimalOwner'(4,'Cecile',turtle),
8 - 'AnimalOwner'(4,'Chelsea',dog)
}
Input: Is this the expected answer for view 'AnimalOwner'?
(y/n/m/mT/w/wN/a/h) [y]: y
Info: Buggy relation found: CatsAndDogsOwner


Fernando Senz-Prez 146/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

In lhis exanpIe, lalIes have leen liusled, lul il is aIso possilIe lo ask lhe usei
foi lhe vaIidily of lhe invoIved lalIes in lhe delugging piocess via lhe connand
/debug_sql Guest trust_tables(no). In lhis exanpIe session, vaIidily of lalIe
Ovnei vouId le asked lo lhe usei.
%.1'.1 Arusted S&eci:ications
In SQL, lhe foIIoving scenaiio is veiy usuaI: A sel of coiiecl vievs is updaled
lo inpiove ils efficiency. The nev sel of vievs incIudes lolh nev vievs and inpioved
veisions of sone oId vievs, keeping lheii nanes and inlended ansveis. Sonelines,
lhe nev, usuaIIy noie invoIved syslen, no Iongei pioduces lhe expecled iesuIls. We
aIIov lo use lhe fiisl, ieIialIe veision, vhich ve caII a trusted specification duiing lhe
sulsequenl delugging session.
Ioi inslance, Iel's considei lhal lhe usei has coiiecled lhe foinei exanpIe,
vhich is nov voiking piopeiIy. Nov, suppose lhal, in oidei lo inpiove ieadaliIily,
lhe sel of vievs is changed ly ienoving AnimalOwner, adding inslead a nev viev
CatOrDogOwner, and nodifying LessThan6 and CatsAndDogsOwner, vhich nov
nake use of CatOrDogOwner.
Nexl, lhe nodified and nev vievs (Guest and NoCommonName ienain lhe
sane, lhis nev veision is Iocaled in fiIe examples/SQLDebugger/pets2.sql) aie
Iisled.

create or replace view CatsOrDogsOwner(id,aname,specie) as
select O.id, P.name, P.specie
from Owner O, Pet P, PetOwner PO
where O.id = PO.id and P.code = PO.code
and (specie='cat' or specie='dog');

create or replace view CatsAndDogsOwner(id,aname) as
select A.id, A.aname
from CatsOrDogsOwner A, CatsOrDogsOwner B
where A.id=B.id and A.specie=B.specie;

create or replace view LessThan6(id) as
select id from CatsOrDogsOwner
group by id having count(*)<6;
The inlended ansvei of lhe vievs vilh lhe sane nane is kepl. In lhe case of
CatOrDogOwner, ils inlended ansvei is lhe nuIlisel of ovneis vilh lheii pel nanes
and species, lul Iiniled lo cals and dogs.
The veiy sane conpulalion liee as foi pets1.sql iesuIls aflei iepIacing
IileiaIs AnimalOwner ly CatOrDogOwner. Hovevei, lhe nev sel of vievs is
eiioneous, since lhe WHERE condilion A.specie=B.specie of CatsAndDogsOwner
shouId le A.specie <> B.specie, in oidei lo ensuie lhal lhe ovnei has al Ieasl one
dog and one cal.
Nov, lhe usei again delecls an unexpecled iesuIl fion lhe viev Guest since ils
oulcone incoiieclIy incIudes lhe ovnei vilh idenlifiei 4: Tom Cohen. A nev
delugging session slails, lul nov lhe oId veision of lhe vievs (in lhe fiIe
pets_trust) can le used as a liusled specificalion as foIIovs:



Fernando Senz-Prez 147/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> /process examples/SQLDebugger/pets2.sql
...
DES> /debug_sql Guest
trust_file('examples/SQLDebugger/pets_trust')

Info: Debugging view 'Guest'.
{
1 - 'Guest'(3,'Robin Scott'),
2 - 'Guest'(4,'Tom Cohen')
}
Input: Is this the expected answer for view 'Guest'?
(y/n/m/mT/w/wN/a/h) [n]: n
Info: view 'NoCommonName' is nonvalid w.r.t. the trusted file.
Info: view 'LessThan6' is valid w.r.t. the trusted file.
Info: view 'CatsAndDogsOwner' is nonvalid w.r.t. the trusted
file.
Info: Debugging view 'CatsOrDogsOwner'.
{
1 - 'CatsOrDogsOwner'(1,'Kitty',cat),
2 - 'CatsOrDogsOwner'(1,'Wilma',dog),
3 - 'CatsOrDogsOwner'(2,'Lucky',dog),
4 - 'CatsOrDogsOwner'(2,'Wilma',cat),
5 - 'CatsOrDogsOwner'(3,'Oreo',cat),
6 - 'CatsOrDogsOwner'(3,'Rocky',dog),
7 - 'CatsOrDogsOwner'(4,'Chelsea',dog)
}
Input: Is this the expected answer for view 'CatsOrDogsOwner'?
(y/n/m/mT/w/wN/a/h) [y]:
Info: Buggy view found: CatsAndDogsOwner
Heie, lhe deluggei liaveises lhe conpulalion liee as lefoie, lul lhe usei is nol
asked foi vievs in lhe sel of liusled vievs, and lhe eiioneous viev is caughl vilh onIy
one finaI check (conpaied lo lhe foui checks lhal vouId le needed olheivise). The
deluggei delecls lhal lhe nev veision of CatsAndDogsOwner is eiioneous.
%.1'.2 Missing and ,rong Au&les
The deluggei aIso aIIovs lhe usei lo specify lhe eiioi lype, indicaling if lheie is
eilhei a nissing ansvei (a lupIe vas expecled lul il is nol in lhe iesuIl) oi a viong
ansvei (lhe iesuIl conlains an unexpecled lupIe). This infoinalion is used foi sIicing
lhe associaled queiies, keeping onIy lhose pails lhal nighl le lhe cause of lhe eiioi.
The vaIidily of lhe iesuIls pioduced ly sIiced queiies is easiei lo deleinine, lhus
faciIilaling lhe Iocalion of lhe eiioi.
%.1'.2.1 Missing Au&les
Lel's considei anolhei foIIoving exanpIe (Iocaled al examples/SQLDebugger
/example1.sql): The IoyaIly piogian of an acadeny avaids an inlensive couise foi
sludenls lhal salisfy lhe foIIoving consliainls:
The sludenl has conpIeled lhe lasic IeveI couise (IeveI = O).
The sludenl has nol conpIeled an inlensive couise.
To conpIele an inlensive couise, a sludenl nusl eilhei pass lhe aII in one couise, oi
lhe lhiee iniliaI IeveI couises (IeveIs 1, 2 and 3).


Fernando Senz-Prez 148/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The dalalase schena incIudes lhiee lalIes:
courses(id,level) conlains infoinalion aloul lhe slandaid couises, incIuding
lheii idenlifiei and lhe couise IeveI
registration(student,course,pass) indicales lhal lhe sludenl is in lhe
couise, vilh pass laking lhe vaIue liue if lhe couise has leen successfuIIy
conpIeled
allInOneCourse(student,pass) conlains infoinalion aloul sludenls
iegisleied in a speciaI inlensive couise, vilh pass pIaying lhe sane ioIe as in
iegislialion.
IiIe example1.sql conlains lhe SQL vievs seIecling lhe avaid candidales.
The fiisl viev is standard, vhich conpIeles lhe infoinalion incIuded in lhe lalIe
iegislialion vilh lhe couise IeveI. The viev basic seIecls lhose slandaid sludenls lhal
have passed a lasic IeveI couise (IeveI O). Viev intensive defines as inlensive
sludenls lhose in lhe lalIe allInOneCourse, logelhei vilh lhe sludenls lhal have
conpIeled lhe lhiee iniliaI IeveIs. Hovevei, lhis viev definilion is eiioneous: We have
foigollen lo check lhal lhe couises have leen conpIeled (fIag pass). IinaIIy, lhe nain
viev awards seIecls lhe sludenls in lhe lasic lul nol in lhe inlensive couises. Suppose
lhal ve liy lhe queiy select * from awards, and lhal in lhe iesuIl ve nolice lhal
lhe sludenl Anna is nissing. We knov lhal Anna conpIeled lhe lasic couise, and lhal
aIlhough she iegisleied in lhe lhiee iniliaI IeveIs, she did nol conpIele one of lhen,
and hence she is nol an inlensive sludenl. Thus, lhe iesuIl ollained ly lhis queiy is
nonvaIid.
So, lhe usei slails lhe deluggei as Anna is nol anong lhe (possilIy Iaige) Iisl of
sludenl nanes pioduced ly viev awards. The delugging session pioceeds as foIIovs:

DES> /process examples/SQLDebugger/awards1
...
DES> /debug_sql awards
Info: Debugging view 'awards'.
{
1 - awards('Carla')
}
Input: Is this the expected answer for view 'awards'?
(y/n/m/mT/w/wN/a/h) [n]: m'Anna'
Info: Debugging view 'intensive'.
Input: Should 'intensive' include a tuple of the form 'Anna'?
(y/n/a) [y]: n
Info: Debugging view 'standard'.
Input: Should 'standard' include a tuple of the form 'Anna,1,1'?
(y/n/a) [y]: y
Info: Debugging view 'standard'.
Input: Should 'standard' include a tuple of the form 'Anna,2,1'?
(y/n/a) [y]: y
Info: Debugging view 'standard'.
Input: Should 'standard' include a tuple of the form 'Anna,3,0'?
(y/n/a) [y]: y
Info: Buggy view found: intensive
The fiisl ansvei m'Anna' indicales lhal (Anna) is nissing in lhe viev
avaids. Nexl, lhe usei indicales lhal viev inlensive shouId nol incIude (Anna). The


Fernando Senz-Prez 14/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

deluggei lhen asks lhiee sinpIe queslions invoIving lhe viev slandaid. Aflei checking
lhe infoinalion foi Anna, lhe usei indicales lhal lhe Iisled lupIes aie coiiecl. Then, lhe
looI poinls oul intensive as lhe luggy viev, aflei onIy five sinpIe queslions.
Olseive lhal inleinediale vievs can conlain hundieds of lhousands of lupIes, lul lhe
sIicing nechanisn heIps lo focus onIy on lhe souice of lhe eiioi.
%.1'.2.2 ,rong Au&les
Lel's considei a nodificalion of lhe dalalase defined in awards1.sql as found
in fiIe awards2.sql, vheie lhe viev basicLevelStudents has leen incoiieclIy
defined. We piocess lhis fiIe, inspecl lhe oulcone of awards and nolice lhal Anna
shouId nol le in lhe iesuIl sel. Then, ve pioceed vilh lhe delugging session as
foIIovs:

DES> /process examples/SQLDebugger/awards2
...
DES> /debug_sql awards
Info: Debugging view 'awards'.
{
1 - awards('Ana'),
2 - awards('Mica')
}
Input: Is this the expected answer for view 'awards'?
(y/n/m/mT/w/wN/a/h) [n]: w1
Info: Debugging view 'intensiveStudents'.
{
1 - intensiveStudents('Juan')
}
Input: Is this the expected answer for view 'intensiveStudents'?
(y/n/m/mT/w/wN/a/h) [y]:
Info: Debugging view 'candidates'.
Input: Should 'candidates' include a tuple of the form 'Ana'?
(y/n/a) [y]: n
Info: Debugging view 'basicLevelStudents'.
Input: Should 'basicLevelStudents' include a tuple of the form
'Ana'? (y/n/a) [y]: n
Info: Debugging view 'salsaStudents'.
Input: Should 'salsaStudents' include a tuple of the form
'Ana,1,teach1'? (y/n/a) [y]:
Info: Debugging view 'salsaStudents'.
Input: Should 'salsaStudents' include a tuple of the form
'Ana,2,teach2'? (y/n/a) [y]:
Info: Debugging view 'salsaStudents'.
Input: Should 'salsaStudents' include a tuple of the form
'Ana,3,teach1'? (y/n/a) [y]:
Info: Buggy view found: basicLevelStudents
%.1'.2.3 Dis&laying E)tended In:ormation
LnalIing veilose oulpul aIIovs lo exlend lhe dispIay vilh fuilhei infoinalion
as, e.g., viev definilions vhen lhey aie asked foi ils vaIidily. As veII, enalIing
deveIopnenl oulpul aIIovs lo check hov lhe Iogic piogian lhal iepiesenls lhe
conpulalion liee is luiIl (c.f. |CCS12aj). Ioi lhal, use lhe foIIoving connands, iesp.:

DES> /verbose on


Fernando Senz-Prez 15!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Info: Verbose output is on.

DES> /development on
Info: Development listings are on.
%.11 S#$ Aest Case !enerator
Checking lhal a viev pioduces lhe sane iesuIl as ils inlended inleipielalion is a
daunling lask vhen Iaige dalalases and lolh dependenl and coiieIaled queiies aie
consideied. Tesl case geneialion piovides lupIes lhal can le nalched lo lhe inlended
inleipielalion of a viev and lheiefoie le used lo calch possilIe design eiiois in lhe
viev.
A lesl case foi a viev in lhe conlexl of a dalalase is a sel of lupIes foi lhe
diffeienl lalIes invoIved in lhe conpulalion of lhe viev. Lxeculing a viev foi a positive
lesl case (ITC)
7
shouId ieluin, al Ieasl, one lupIe. This lupIe can le used ly lhe usei lo
calch eiiois in lhe viev, if any. This vay, if lhe usei delecls lhal lhis lupIe shouId nol
le pail of lhe ansvei, il is definileIy a vilness of lhe eiioi in lhe design of lhe viev. On
lhe conliaiy, lhe execulion of lhe viev foi a negative lesl case (NTC) shouId ieluin al
Ieasl one lupIe vhich shouId nol le in lhe iesuIl sel of lhe queiy. Again, if no such a
lupIe can le found, lhis lupIe is a vilness of lhe eiioi in lhe design.
A ITC in a lasic queiy neans lhal al Ieasl one lupIe in lhe queiy donain
salisfies lhe where condilion. In lhe case of aggiegale queiies, a ITC viII iequiie
finding a vaIid aggiegale veiifying lhe having condilion, vhich in luin inpIies lhal
aII ils iovs veiify lhe where condilion.
In lhe case of lasic queiy, a NTC viII conlain al Ieasl one lupIe in lhe iesuIl sel
of lhe viev nol veiifying lhe where condilion. In queiies conlaining aggiegale
funclions, lhis lupIe eilhei does nol salisfy eilhei lhe where condilion oi lhe having
condilion. Sel opeialions aie aIso aIIoved in lolh ITC and NTC geneialion.
Il is possilIe lo ollain a lesl case vhich is lolh posilive and negalive al lhe
sane line lhus achieving predicate coverage vilh iespecl lo lhe vheie and having
cIauses (in lhe sense of |AOO8j). We viII caII lhese lesls INTCs. Ioi inslance, considei
lhe foIIoving syslen session:

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)]
The lesl case |t(5),t(4) is a INTC. Hovevei, a INTC is nol aIvays possilIe
lo le geneialed. Ioi inslance, il is possilIe foi lhe foIIoving viev lo geneiale lolh
ITCs and NTCs lul no INTC:

create view v(a) as
select a
from t
where a=1 and not exists (select a from t where a<>1);

7
Thal is, execuling lhe viev using as inpul dala foi lhe lalIes lhose in lhe ITC.


Fernando Senz-Prez 151/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The onIy one ITC foi lhis viev is |t(1) (noduIo dupIicales). Theie aie nany
NTCs, as, e.g., |t(2) and |t(1) ,t(2).
The connand /test_case View [Options] aIIovs lvo kind of oplions:
fiisl, lo specify vhich class of lesl case is lo le geneialed: all (INTC, lhe defauIl
oplion), positive (ITC) oi negative (NTC). The second oplion specifies an action:
lhe iesuIls aie lo le dispIayed via lhe oplion display (defauIl oplion), added lo lhe
coiiesponding lalIes (add oplion) oi lhe conlenls of lhe lalIes iepIaced ly lhe
geneialed lesl case lupIes (replace oplion).
Ioi expeiinenling vilh lhe donain of alliilules, ve piovide lhe connand
/tc_domain Min Max, vhich defines de iange of vaIues lhe inlegei alliilules nay
lake. This iange is deleininanl in lhe seaich of lesl cases in a consliainl nelvoik lhal
can easiIy lecone loo conpIex as Iong as invoIved vievs giov. So, keeping lhis
donain snaII aIIovs lo nanage liggei piolIens.
Sliing conslanls occuiiing in aII lhe vievs on vhich lhe viev foi lhe lesl case
geneialed depends aie napped lo inlegeis in lhe sane donain, slailing fion O. So, lhe
size of lhe donain has lo le Iaigei enough lo hoId, al Ieasl, lhe sliing conslanls in lhose
vievs.
AIso, ve piovide lhe connand /tc_size Min Max foi specifying lhe size of
lhe lesl case geneialed, in nunlei of lupIes. Again, keeping lhis vaIue snaII heIps in
leing alIe lo cope vilh liggei piolIens.
CuiienlIy, ve piovide suppoil foi inlegei and sliing alliilules. inaiy
disliilulions, and lolh SICSlus and SWI-IioIog souice disliilulions aIIov lhe
funclionaIily desciiled.
%.12 4atc/ ?rocessing
Theie aie lvo vays foi piocessing lalch fiIes:
1. If lhe fiIe des.ini is Iocaled al lhe disliilulion diiecloiy, ils conlenls aie
inleipieled as inpul pionpls and execuled lefoie giving conlioI lo lhe usei al slail-
up of lhe syslen.
2. The connand /process filename (oi /p as a shoilhand) aIIovs lo piocess each
Iine in lhe fiIe as il vas an inpul, lhe sane vay as lefoie. If no fiIe exlension is
given and filename does nol exisls, lhen .ini, .sql, and .ra aie appended in
luin lo fiIenane and liied in lhal oidei foi finding an exisling fiIe.
When piocessing lalch fiIes, pionpl inpuls slailing vilh lhe synloI % aie
inleipieled as connenls. This vay, lhe lalch fiIe des.ini nay conlain connenls. The
usei can aIso inleiacliveIy inpul such connenls, lul again pioduce no effecls.
alch piocessing can incIude Iogging lo pioduce oulpul. This is usefuI lo feed
lhe syslen vilh lalch inpul and gel ils oulpul in a fiIe, nayle avoiding any inleiaclive
inpul. Ioi exanpIe, considei lhe foIIoving des.ini exceipl:

% Dump output to output.txt
/log output.txt
/pretty_print off
% Process (Datalog, SQL, ... queries and commands)
/c examples/fib


Fernando Senz-Prez 152/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

fib(100,F)
% End log
/nolog
The iesuIl found in oulpul.lxl shouId le (noduIo lIank Iines):

DES> /pretty_print off
Info: Pretty print is off.
DES> % Process (Datalog, SQL, ... queries and commands)
DES> /c examples/fib
Warning: N > 1 may raise a computing exception if non-ground at
run-time.
Warning: N2 is N - 2 may raise a computing exception if non-
ground at run-time.
Warning: N1 is N - 1 may raise a computing exception if non-
ground at run-time.
Warning: Next rule is unsafe because of variable(s):
[N]
fib(N,F) :- N > 1,N2 is N - 2,fib(N2,F2),N1 is N -
1,fib(N1,F1),F is F2 + F1.
DES> fib(100,F)
{
fib(100,573147844013817084101)
}
Info: 1 tuple computed.
DES> % End log
DES> /nolog
%.13 Messages
DLS syslen nessages aie piefixed ly:
Info: An infoinalion nessage vhich iequiies no allenlion fion lhe usei. SeveiaI
infoinalion nessages aie hidden vilh lhe connand /verbose off, vhich is lhe
defauIl node.
Warning: A vaining nessage vhich does nol necessaiiIy inpIy an eiioi, lul lhe
usei is iequesled lo focus on ils oiigin. These nessages aie aIvays shovn.
Error: An eiioi nessage vhich iequiies allenlion fion lhe usei. These nessages
aie aIvays shovn.
Exception: An exceplion nessage vhich iequiies allenlion fion lhe usei. These
nessages aie aIvays shovn. LxanpIes of exceplion nessages incIude inslanlialion
eiiois and undefined piedicales.
IioIog exceplions aie caughl ly DLS and shovn lo lhe usei vilhoul any fuilhei
piocessing. Depending on lhe IioIog pIalfoin, lhe syslen nay conlinue ly ilseIf,
olheivise lhe usei nusl lype des. (incIuding lhe ending dol) lo conlinue. Upon
exceplions, lhe exlension lalIe is cIeaied and slialificalion is ieconpuled. Nole lhal lhe
Iallei conpulalion nay lake a Iong line if lheie aie nuIlipIe lalIes and vievs
(lypicaIIy in opened ODC conneclions foi DMSs as OiacIe and SQL Seivei).


Fernando Senz-Prez 153/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

%.14 Commands
The inpul al lhe pionpl (i.e., connands oi queiies) nusl le viillen in a Iine
(i.e., vilhoul caiiiage ieluins, aIlhough il can le lioken ly lhe DLS consoIe due lo
space Iinilalions) and can end vilh an oplionaI dol.
Connands aie issued ly pieceding lhe connand vilh a sIash (/) al lhe DLS
syslen pionpl. Connand aigunenls aie nol a conna-sepaialed Iisl encIosed
lelveen liackels as usuaI, lul lhey sinpIy occui sepaialed ly al Ieasl one lIank. This
enalIes shoil lyping.
Connand nanes and linaiy fIags (on/off svilches) aie nol case sensilive.
Lnding dols aie consideied as pail of lhe aigunenl vheievei lhey aie expecled.
Ioi inslance, /cd .. lehaves as /cd ... (lhis connand changes lhe voiking
diiecloiy lo lhe paienl diiecloiy). In lhis Iasl case, lhe finaI dol is nol consideied as pail
of lhe aigunenl. The connand /ls . shovs lhe conlenls of lhe voiking diiecloiy,
vheieas /ls .. shovs lhe conlenls of lhe paienl diiecloiy (vhich lehaves as /ls
...).
IiIenanes and diiecloiies can le specified vilh ieIalive oi alsoIule nanes.
Theie is no need of encIosing such nanes lelveen sepaialois. Ioi inslance, fiIe oi
diiecloiy nanes can conlain lIanks (foi Windovs useis) and you neilhei need lo use
doulIe quoles noi aie aIIoved lo use lhen.
Since connands aie sulnilled vilh a pieceding sIash, lhey aie onIy iecognized
as connands in lhis vay. Theiefoie, you can use connand nanes foi youi ieIalion
nanes vilhoul nane cIashes.
When consuIling DalaIog fiIes, fiIenane iesoIulion voiks as foIIovs:
If lhe given fiIenane ends vilh .dl, DLS liies lo Ioad lhe fiIe vilh lhis (alsoIule oi
ieIalive) fiIenane.
If lhe given fiIenane does nol end vilh .dl, DLS fiislIy liies lo Ioad a fiIe vilh .dI
appended lo lhe end of lhe fiIenane. If such a fiIe is nol found, il liies lo Ioad lhe
fiIe vilh lhe given fiIenane.
In connand aigunenls, vhen appIicalIe, you can use ieIalive oi alsoIule
palhnanes. In geneiaI, you can use a sIash (/) as a diiecloiy deIinilei, lul depending
on lhe pIalfoin, you can aIso use lhe lacksIash (\). AIso, il nighl le needed lo encIose
palhnanes lelveen singIe quoles (').
See Seclion 4.1.2 foi infoinalion aloul DLS queiies.
Sone connands aie IaleIIed vilh TAPI enabled, vhich neans lhal lhey can le
sulnilled lo lhe lexluaI appIicalion piogianning inleiface (TAII). Theie is addilionaI
infoinalion foi such connands in Seclion 5.15.2.
Nexl, connands aie desciiled, vheie ilaIics indicale a paianelei vhich nusl
le suppIied ly lhe usei. Squaie liackels indicale an oplionaI keyvoid oi paianelei
(excepling lhe fiisl lvo DLS Dalalase connands foi consuIling and ieconsuIling fiIes,
foIIoving IioIog synlax). If a paianelei is nol accepled, pIease liy again encIosing il
lelveen singIe quoles (').


Fernando Senz-Prez 154/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

%.14.1 DES Data*ase
/[FileNames]
Load lhe DalaIog piogians found in lhe conna-sepaialed Iisl [Filenames],
discaiding lolh iuIes aIieady Ioaded, inlegiily consliainls, and SQL lalIe and
viev definilions. The exlension lalIe is cIeaied, and lhe piedicale dependency
giaph and sliala aie ieconpuled.
LxanpIes:
Assuning ve aie on lhe exanpIes disliilulion diiecloiy, ve can viile:
DES> /[mutrecursion,family]
TAPI enabled"
%ee also /consult Filename.
/[+FileNames]
Load lhe DalaIog piogians found in lhe conna-sepaialed Iisl Filenames,
keeping iuIes aIieady Ioaded, inlegiily consliainls, and SQL lalIe and viev
definilions. The exlension lalIe is cIeaied, and lhe piedicale dependency giaph
and sliala aie ieconpuled.
TAPI enabled"
%ee also /[Filenames].
/abolish
DeIele lhe DalaIog dalalase. This incIudes aII lhe IocaI iuIes (incIuding lhose
vhich aie lhe iesuIl of SQL conpiIalions) and exleinaI iuIes (peisisled
piedicales). Inlegiily consliainls, and SQL lalIe and viev definilions aie
ienoved. The exlension lalIe is cIeaied, and lhe piedicale dependency giaph
and sliala aie ieconpuled.
/abolish Name
DeIele lhe piedicales nalching Name. This incIudes aII lheii IocaI iuIes
(incIuding lhose vhich aie lhe iesuIl of SQL conpiIalions) and exleinaI iuIes
(peisisled piedicales). Theii inlegiily consliainls, and SQL lalIe and viev
definilions aie ienoved. The exlension lalIe is cIeaied, and lhe piedicale
dependency giaph and sliala aie ieconpuled.
/abolish Name/Arity
DeIele lhe piedicales nalching lhe pallein Name/Arity. This incIudes aII lheii
IocaI iuIes (incIuding lhose vhich aie lhe iesuIl of SQL conpiIalions) and
exleinaI iuIes (peisisled piedicales). Theii inlegiily consliainls, and SQL lalIe
and viev definilions aie ienoved. The exlension lalIe is cIeaied, and lhe
piedicale dependency giaph and sliala aie ieconpuled.
/assert Head[:-Body]
Add a DalaIog iuIe. If Body is nol specified, il is sinpIy a facl. RuIe oidei is
iiieIevanl foi DalaIog conpulalion. The exlension lalIe is cIeaied, and lhe
piedicale dependency giaph and sliala aie ieconpuled.
/consult FileName
Load lhe DalaIog piogian found in lhe fiIe Filename, discaiding lhe iuIes
aIieady Ioaded, inlegiily consliainls, and SQL lalIe and viev definilions. The
exlension lalIe is cIeaied, and lhe piedicale dependency giaph and sliala aie
ieconpuled. The defauIl exlension .dl foi DalaIog piogians can le onilled.
LxanpIes:


Fernando Senz-Prez 155/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Assuning ve aie on lhe disliilulion diiecloiy, ve can viile:
DES> /consult examples/mutrecursion
vhich lehaves lhe sane as lhe foIIoving:
DES> /consult examples/mutrecursion.dl
DES> /consult ./examples/mutrecursion
DES> /consult c:/des3.4/examples/mutrecursion.dl
This Iasl connand assunes lhal lhe disliilulion diiecloiy is c:/des3.4.
%ynonyms: /c, /restore_ddb.
TAPI enabled"
/check_db
Check dalalase consislency v.i.l. decIaied inlegiily consliainls (lypes,
exislency, piinaiy key, candidale key, foieign key, funclionaI dependency, and
usei-defined). DispIay a iepoil vilh lhe oulcone
/des Input
Ioice DLS lo soIve Input. If Input is an SQL queiy, DLS soIves il inslead of
ieIying on exleinaI DMS soIving. This aIIovs lo liy lhe noie expiessive
queiies vhich aie avaiIalIe in DLS (as, e.g., hypolhelicaI and non-Iineai
iecuisive queiies)
/drop_ic Constraint
Diop lhe specified inlegiily consliainl, vhich slails vilh ":-" and can le eilhei
one of:
:- type(Table, [Column:Type])
:- nn(Table, Columns)
:- pk(Table, Columns)
:- ck(Table, Columns)
:- fk(Table, Columns, RTable, RColumns)
:- fd(Table, Columns, DColumns)
:- Goal
vheie CoaI specifies a usei-defined inlegiily consliainl). OnIy one consliainl
can le diopped al a line. AIleinalive synlax foi consliainl is aIso aIIoved.
TAPI enabled"
/listing
Lisl lhe Ioaded DalaIog iuIes. Neilhei inlegiily consliainls noi SQL vievs and
neladala aie dispIayed.
/listing Name
Lisl lhe Ioaded DalaIog iuIes nalching Name. Neilhei inlegiily consliainls noi
SQL vievs and neladala aie dispIayed.
/listing Name/Arity
Lisl lhe Ioaded DalaIog iuIes nalching lhe pallein Name/Arity. Neilhei
inlegiily consliainls noi SQL vievs and neladala aie dispIayed.
/listing Head
Lisl lhe DalaIog Ioaded iuIes vhose heads aie sulsuned ly lhe head Head.
Neilhei inlegiily consliainls noi SQL vievs and neladala aie dispIayed.
/listing Head:-Body
Lisl lhe DalaIog Ioaded iuIes lhal aie sulsuned ly Head:-Body. Neilhei
inlegiily consliainls noi SQL vievs and neladala aie dispIayed.


Fernando Senz-Prez 156/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

/list_modes
Lisl lhe expecled nodes foi unsafe piedicales in oidei lo le coiieclIy
conpuled. Modes can le 'i' (foi an inpul aigunenl) and 'o' (foi an oulpul
aigunenl)
/list_modes Name
Lisl expecled nodes, if any, foi piedicales vilh nane Name in oidei lo le
coiieclIy conpuled. Modes can le 'i' (foi an inpul aigunenl) and 'o' (foi an
oulpul aigunenl)
/list_modes Name/Arity
Lisl expecled nodes, if any, foi lhe given piedicale Name/Arity in oidei lo le
coiieclIy conpuled. Modes can le 'i' (foi an inpul aigunenl) and 'o' (foi an
oulpul aigunenl)
/reconsult FileName
Load a DalaIog piogian found in lhe fiIe Filename, keeping lhe iuIes aIieady
Ioaded. The exlension lalIe is cIeaied, and lhe piedicale dependency giaph and
sliala aie ieconpuled.
TAPI enabled"
%ee also /consult Filename.
%ynonyms: /r.
/restore_ddb Filename
Resloie lhe DalaIog dalalase in lhe given fiIe (sane as consult) . Consliainls
(lype, nuIIaliIily, piinaiy key, candidale key, funclionaI dependency, foieign
key, and usei-defined) aie aIso iesloied, if piesenl in Filename
/retract Head[:-Body]
DeIele lhe fiisl DalaIog iuIe lhal unifies vilh Head:-Body (oi sinpIy vilh
Head, if Body is nol specified. In lhis case, onIy facls aie deIeled). The exlension
lalIe is cIeaied, and lhe piedicale dependency giaph and sliala aie
ieconpuled.
/retractall Head
DeIele aII lhe DalaIog iuIes vhose heads unify vilh Head. The exlension lalIe
is cIeaied, and lhe piedicale dependency giaph and sliala aie ieconpuled.
/save_ddb [force] Filename
Save lhe cuiienl DalaIog dalalase lo lhe fiIe Filename. If oplion force is
incIuded, no queslion is asked lo lhe usei shouId lhe fiIe exisls aIieady.
Consliainls (lype, nuIIaliIily, piinaiy key, candidale key, funclionaI
dependency, foieign key, and usei-defined) aie aIso saved
%.14.2 =D4C Data*ase
/open_db Name [Options]
Open and sel lhe cuiienl ODC conneclion lo Name, vheie
Options=|user(Username)j |password(Password)j. This conneclion
nusl le aIieady defined al lhe OS Iayei.
TAPI enabled
/close_db
CIose lhe cuiienl ODC conneclion.


Fernando Senz-Prez 157/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

TAPI enabled
/close_db Name
CIose lhe given ODC conneclion.
TAPI enabled
/current_db
DispIay lhe cuiienl ODC conneclion nane and DSN piovidei.
TAPI enabled
/show_dbs
DispIay lhe open dalalase conneclions.
TAPI enabled
/use_db Name
Make Name lhe cuiienl ODC conneclion.
TAPI enabled
/use_ddb
Shoilhand foi /use_db $des.
TAPI enabled
%.14.3 De*ugging and Aest Case !eneration
/debug_datalog Goal [Level]
Slail lhe deluggei foi lhe lasic goaI Goal al piedicale oi cIause IeveIs, vhich is
indicaled vilh lhe oplions p and c foi Level, iespecliveIy. DefauIl is p.
/debug_sql View [Options]
Delug an SQL viev vheie:
Options=[trust_tables([yes|no])] [trust_file(FileName)]
DefauIls aie liusl lalIes and no liusl fiIe. Il nighl le needed lo encIose
FileName lelveen singIe quoles.
/trace_datalog Goal [Order]
Tiace a DalaIog goaI in lhe given oidei (postorder oi lhe defauIl preorder).
/trace_sql View [Order]
Tiace an SQL viev in lhe given oidei (postorder oi lhe defauIl preorder).
/test_case View [Options]
Ceneiale lesl case cIasses foi lhe viev View. Options nay incIude a cIass
and/oi an aclion paianeleis. The lesl case cIass is indicaled ly lhe vaIues all
(posilive-negalive, lhe defauIl), positive, oi negative in lhe cIass
paianelei. The aclion is indicaled ly lhe vaIues display (onIy dispIay lupIes,
lhe defauIl), replace (iepIace conlenls of lhe invoIved lalIes ly lhe conpuled
lesl case), oi add (add lhe conpuled lesl case lo lhe conlenls of lhe invoIved
lalIes) in lhe aclion paianelei.
/tc_size Min Max
Sel lhe nininun and naxinun nunlei of lupIes geneialed foi a lesl case.
/tc_size
DispIay lhe nininun and naxinun nunlei of lupIes geneialed foi a lesl case.
/tc_domain Min Max
Sel lhe donain of vaIues foi lesl cases lelveen Min and Max.


Fernando Senz-Prez 158/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

/tc_domain
DispIay lhe donain of vaIues foi lesl cases.
%.14.4 Aa*ling
/clear_et
DeIele lhe conlenls of lhe exlension lalIe.
/list_et
Lisl lhe conlenls of lhe exlension lalIe in IexicogiaphicaI oidei. Iiisl, ansveis
aie dispIayed, lhen caIIs.
/list_et Name
Lisl lhe conlenls of lhe exlension lalIe nalching Name. Iiisl, ansveis aie
dispIayed, lhen caIIs.
/list_et Name/Arity
Lisl lhe conlenls of lhe exlension lalIe nalching lhe pallein Name/Arity. Iiisl,
ansveis aie dispIayed, lhen caIIs.
%.14.% =&erating System
/cat Filename
Type lhe conlenls of Filename encIosed lelveen lhe foIIoving Iines:
%% BEGIN AbsoluteFilename %%
%% END AbsoluteFilename %%
%ynonym: /type Filename.
/cd Path
Sel lhe cuiienl diiecloiy lo Path.
TAPI enabled"
/cd
Sel lhe cuiienl diiecloiy lo lhe diiecloiy vheie DLS vas slailed fion.
TAPI enabled"
/edit Filename
Ldil Filename ly caIIing lhe piedefined exleinaI lexl ediloi. This ediloi is sel
vilh lhe connand /set_editor
/pwd
DispIay lhe alsoIule fiIenane foi lhe cuiienl diiecloiy.
TAPI enabled"
/ls
DispIay lhe conlenls of lhe cuiienl diiecloiy in aIphalelicaI oidei. Iiisl, fiIes aie
dispIayed, lhen diiecloiies.
%ynonym: /dir.
/ls Path
DispIay lhe conlenls of lhe given diiecloiy in aIphalelicaI oidei. Il lehaves as
/ls.
%ynonym: /dir Path.
/set_editor
DispIay lhe cuiienl exleinaI lexl ediloi


Fernando Senz-Prez 15/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

/set_editor Editor
Sel lhe cuiienl exleinaI lexl ediloi lo Editor
/shell Command
Sulnil Command lo lhe opeialing syslen sheII.
*otes for platform specific issues+
o Windovs useis:
command.exe is lhe sheII foi Windovs 98, vheieas cmd.exe is lhe one foi
Windovs NT/2OOO/2OO3/XI/Visla/7.
o SICSlus useis:
Undei Windovs, if lhe enviionnenl vaiialIe SHELL is defined, il is
expecled lo nane a Unix Iike sheII, vhich viII le invoked vilh lhe oplion -
c Command. If SHLLL is nol defined, lhe sheII naned ly COMSPEC viII le
invoked vilh lhe oplion /C Command.
o Windovs and Linux/Unix execulalIe useis:
The sane nole foi SICSlus is appIied.
%ynonyms: /s.
/rm FileName
DeIele FileName fion lhe fiIe syslen.
%ynonyms: /del.
%.14." $og
/log
DispIay lhe cuiienl Iog fiIe, if any.
/log Filename
Sel lhe cuiienl Iog lo lhe given fiIenane and node: write (oveiviile exisling
fiIe, if any, oi cieales a nev one) oi append (append lo lhe conlenls of lhe
exisling fiIe).
/nolog
DisalIe Iogging.
%.14.( In:ormati0e
/apropos Keyword
DispIay delaiIed heIp aloul Keyword, vhich can le a connand oi luiIl-in.
%ynonyms: /help.
/builtins
Lisl piedefined opeialois, funclions, and piedicales.
/check
DispIay vhelhei inlegiily consliainl checking is enalIed.
/compact_listings
DispIay vhelhei conpacl Iislings aie enalIed.
/dbschema
DispIay lhe dalalase schena: Dalalase nane, lalIes, vievs and DalaIog
consliainls. A DalaIog inlegiily consliainl is dispIayed undei a lalIe if il onIy
iefeis lo lhis lalIe, and undei lhe DalaIog inlegiily consliainls olheivise. If a


Fernando Senz-Prez 16!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

consliainl is ciealed vilh a CREATE TABLE Tablename slalenenl, il is Iisled
undei lhe lalIe Tablename even vhen il iefeis lo olhei lalIes oi vievs
TAPI enabled
%ynonyms: /db_schema.
/dbschema Name
DispIay lhe dalalase schena foi lhe given conneclion, viev oi lalIe nane.
TAPI enabled
%ynonyms: /db_schema.
/dbschema Connection:Name
DispIay lhe dalalase schena foi lhe given viev oi lalIe nane in lhe given
conneclion.
TAPI enabled
%ynonyms: /db_schema.
/dependent_relations Relation
DispIay lhe nane of ieIalions lhal diieclIy depend on ieIalion Relation/Arity.
TAPI enabled
/dependent_relations Relation/Arity
DispIay in foinal Nane/Aiily lhose ieIalions lhal diieclIy depend on ieIalion
Relation/Arity.
TAPI enabled
/des_sql_solving
DispIay vhelhei DLS is foiced lo soIve SQL queiies foi exleinaI Ds. If
enalIed, lhis aIIovs lo expeiinenl vilh noie expiessive queiies as, e.g.,
hypolhelicaI and non-Iineai iecuisive queiies laigeled al an exleinaI DMS.
/des_sql_solving Switch
LnalIe oi disalIe DLS soIving foi SQL queiies vhen lhe cuiienl dalalase is an
open ODC conneclion (on oi off, iesp.)
/development
DispIay vhelhei deveIopnenl Iislings aie enalIed.
/development Switch
LnalIe oi disalIe deveIopnenl Iislings (on oi off, iesp.). These Iislings shov
lhe souice-lo-souice liansIalions needed lo handIe nuII vaIues, DalaIog oulei
join luiIl-ins, and disjunclive IileiaIs.
/duplicates
DispIay vhelhei dupIicales aie enalIed.
/hypothetical
DispIay vhelhei hypolhelicaI queiies aie enalIed (on) oi nol (off)
/nulls
DispIay vhelhei nuIIs aie enalIed (on) oi nol (off)
/sql_left_delimiter
DispIay lhe SQL Iefl deIinilei as defined ly lhe cuiienl dalalase nanagei
(eilhei DLS oi lhe exleinaI DMS via ODC).
TAPI enabled


Fernando Senz-Prez 161/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

/sql_right_delimiter
DispIay lhe SQL Iefl deIinilei as defined ly lhe cuiienl dalalase nanagei
(eilhei DLS oi lhe exleinaI DMS via ODC) .
TAPI enabled
/help
DispIay iesuned heIp on connands.
%horthands: /h.
/help Keyword
DispIay delaiIed heIp aloul Keyword, vhich can le a connand oi luiIl-in.
%ynonyms: /apropos.
/is_empty relation_name
DispIay $true if lhe given ieIalion is enply, and $false olheivise.
TAPI enabled
/list_tables
Lisl lalIe nanes.
TAPI enabled
/list_table_schemas
Lisl lalIe schenas.
TAPI enabled
/list_table_constraints table_name
Lisl lalIe consliainls foi table_name.
TAPI enabled
/list_views
Lisl viev nanes.
TAPI enabled
/list_view_schemas
Lisl viev schenas.
TAPI enabled
/negation
DispIay lhe seIecled aIgoiilhn foi soIving negalion (strata oi et_not).
/pdg
DispIay lhe cuiienl piedicale dependency giaph.
TAPI enabled
/pdg Name
DispIay lhe cuiienl piedicale dependency giaph iesliicled lo lhe fiisl piedicale
found vilh nane Name.
TAPI enabled
/pdg Name/Arity
DispIay lhe cuiienl piedicale dependency giaph iesliicled lo lhe piedicale vilh
nane Name and Arity.
TAPI enabled
/pretty_print
DispIay vhelhei pielly piinl Iislings is enalIed.


Fernando Senz-Prez 162/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

/pretty_print Switch
LnalIe oi disalIe pielly piinl foi Iislings (on oi off, iesp.)
/prompt
DispIay lhe pionpl foinal.
/prompt Switch
Sel lhe foinal of lhe pionpl. The vaIue des sels lhe pionpl lo DES>. The vaIue
des_db adds lhe cuiienl dalalase nane DB as DES:DB>. IinaIIy, plain sels
lhe pionpl lo >. Nole lhal, in any case, if a Ianguage olhei lhan DalaIog is
seIecled, lhe Ianguage nane is aIso dispIayed lefoie >.
/referenced_relations Relation
DispIay lhe nane of ieIalions lhal aie diieclIy iefeienced ly a foieign key in
ieIalion Relation.
TAPI enabled
/referenced_relations Relation/Arity
DispIay in foinal Nane/Aiily lhose ieIalions lhal aie diieclIy iefeienced ly a
foieign key in ieIalion Relation/Arity.
TAPI enabled
/relation_exists relation_name
DispIay $true if lhe given ieIalion exisls, and $false olheivise.
TAPI enabled
/relation_schema relation_name
DispIay ieIalion schena of relation_name.
TAPI enabled
/running_info
DispIay vhelhei iunning infoinalion (as lhe incienenlaI nunlei of consuIled
iuIes as lhey aie iead) is lo le dispIayed.
/running_info Switch
LnalIe oi disalIe dispIay of iunning infoinalion (on oi off, iesp.)
/safe
DispIay vhelhei safely liansfoinalion is enalIed.
/simplification
DispIay vhelhei piogian sinpIificalion is enalIed.
/show_compilations
DispIay vhelhei conpiIalions fion SQL DQL slalenenls lo DalaIog iuIes aie lo
le dispIayed.
/show_compilations Switch
LnalIe oi disalIe dispIay of exlended infoinalion aloul conpiIalion of SQL
DQL slalenenls lo DalaIog cIauses (on oi off, iesp.)
/show_sql
DispIay vhelhei SQL slalenenls vhich aie senl lo an exleinaI dalalase aie lo
le dispIayed
/show_sql Switch


Fernando Senz-Prez 163/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

LnalIe oi disalIe dispIay of SQL slalenenls vhich aie senl lo an exleinaI
dalalase (on oi off, iesp.)
/status
DispIay lhe cuiienl syslen slalus, i.e., veilose node, lhe seIecled negalion
aIgoiilhn, Iogging, eIapsed line dispIay, piogian liansfoinalion, and syslen
veision.
/strata
DispIay lhe cuiienl slialificalion as a Iisl of paiis (IiedNane/Aiily, Slialun).
/timing
DispIay vhelhei eIapsed line dispIay is enalIed.
/timing Switch
DisalIe oi enalIe eilhei a lasic oi delaiIed eIapsed line dispIay (off, on,
detailed, iesp.)
/format_timing
DispIay vhelhei foinalled lining is enalIed.
/format_timing Switch
LnalIe oi disalIe foinalled lining (on oi off, iesp.). Civen lhal ms, s, m, h
iepiesenl niIIiseconds, seconds, ninules, and houis, iespecliveIy, lines Iess
lhan 1 second aie dispIayed as ms, lines lelveen 1 second and Iess lhan 6O aie
dispIayed as s.ms, lines lelveen 6O seconds and Iess lhan 6O ninules aie
dispIayed as m:s.ms, and lines fion 6O ninules on aie dispIayed as
h:m:s.ms
/verbose
DispIay vhelhei veilose oulpul is eilhei enalIed oi disalIed (on oi off, iesp.)
/verbose Switch
LnalIe oi disalIe veilose oulpul nessages (on oi off, iesp.)
/version
DispIay lhe cuiienl DLS syslen veision.
%.14.8 #uery $anguages
/datalog
Svilch lo DalaIog inleipielei (aII queiies aie paised and execuled fiisl ly
DalaIog engine. If il is nol a DalaIog queiy, lhen il is liied fiisl as an SQL
slalenenl. If il is neilhei SQL, finaIIy il is liied as an RA expiession).
/datalog Query
Tiiggei DalaIog iesoIulion foi lhe queiy Query (lhe queiy is paised and
execuled in DalaIog, lul if a paising eiioi is found, il is liied fiisl as an SQL
slalenenl and second as an RA expiession).
/hypothetical Switch
LnalIe oi disalIe hypolhelicaI queiies (on oi off, iesp.)
/nulls Switch
LnalIe oi disalIe nuIIs (on oi off, iesp.)
/prolog


Fernando Senz-Prez 164/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Svilch lo IioIog inleipielei (aII queiies aie paised and execuled in IioIog).
/prolog Goal
Tiiggei IioIogs SLD iesoIulion foi lhe goaI Goal.
/ra
Svilch lo RA inleipielei (aII queiies aie paised and execuled in RA).
/ra Query
Tiiggei RA evaIualion foi lhe queiy Query.
/sql
Svilch lo SQL inleipielei (aII queiies aie paised and execuled in SQL).
/sql SQL_statement
Tiiggei SQL iesoIulion foi SQL_statement.
%.14. A2?IGrelated
See aIso Seclion 5.15.2 foi noie infoinalion.
/tapi Input
Iiocess Input and foinal ils oulpul foi TAII connunicalion. OnIy a Iiniled
sel of possilIe inpuls aie aIIoved (cf. Seclion 5.15)
/test_tapi
Tesl lhe cuiienl TAII conneclion
TAPI enabled
%.14.1' Miscellanea
/check Switch
LnalIe oi disalIe inlegiily consliainl checking (on oi off, iesp.)
/compact_listings Switch
LnalIe oi disalIe conpacl Iislings (on oi off, iesp.)
/display_answer
DispIay vhelhei dispIay of conpuled lupIes is enalIed
/display_answer Switch
LnalIe oi disalIe dispIay of conpuled lupIes (on oi off, iesp.) The nunlei of
lupIes is sliII dispIayed
/display_nbr_of_tuples
DispIay vhelhei dispIay of lhe nunlei of conpuled lupIes is enalIed
/display_nbr_of_tuples Switch
LnalIe oi disalIe dispIay of lhe nunlei of conpuled lupIes (on oi off, iesp.)
/duplicates Switch
LnalIe oi disalIe inlegiily consliainl checking (on oi off, iesp.)
/negation Algorithm
Sel lhe iequiied Algorithm foi soIving negalion (strata oi et_not) .
/halt
Quil lhe syslen.


Fernando Senz-Prez 165/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

%ynonyms: /quit, /q, /exit, /e.
/nulls
DispIay vhelhei nuIIs aie enalIed
/nulls Switch
LnalIe oi disalIe nuIIs (on oi off, iesp.)
/multiline
DispIay vhelhei nuIli-Iine inpul is enalIed.
/multiline Switch
LnalIe oi disalIe nuIli-Iine inpul (on oi off iesp.)
/order_answer
DispIay vhelhei dispIayed ansveis aie oideied ly defauIl
/order_answer Switch
LnalIe oi disalIe a defauIl (ascending) oideiing of dispIayed conpuled lupIes
(on oi off, iesp.) This oidei is oveiiided if lhe usei queiy conlains eilhei a
gioup ly specificalion oi a caII lo a viev vilh such a specificalion
/output Switch
LnalIe oi disalIe dispIay oulpul (on oi off, iesp.)
/process Filename
Iiocess lhe conlenls of Filename as if lhey veie lyped al lhe syslen pionpl.
Lxlensions ly defauIl aie: .sql and .ini. When Iooking foi a fiIe f, lhe
foIIoving fiIenanes aie checked in lhis oidei: f, f.sql, and f.ini.
%ynonyms: /p.
/restore_default_status
Resloie lhe slalus of lhe syslen lo lhe iniliaI slalus, i.e., sel aII usei-configuialIe
fIags lo lheii iniliaI vaIues, incIuding lhe defauIl dalalase and lhe slail-up
diiecloiy
/safe Switch
LnalIe oi disalIe piogian liansfoinalion (on oi off, iesp.)
/simplification Switch
LnalIe oi disalIe piogian sinpIificalion (on oi off, iesp.). RuIes vilh
equaIilies, true, and not(BooleanValue) aie sinpIified.
/statistics Keyword
DispIay slalislics foi Keyword (runtime oi total_runtime). Ioi runtime,
lhis connand dispIays lhe CIU line used vhiIe execuling, excIuding line
spenl in nenoiy nanagenenl lasks oi in syslen caIIs since lhe Iasl caII lo lhis
connand. Ioi total_runtime , lhis connand dispIays lhe lolaI CIU line
used vhiIe execuling, incIuding nenoiy nanagenenl lasks such as gailage
coIIeclion lul excIuding syslen caIIs since lhe Iasl caII lo lhis connand.
/start_stopwatch
Slail slopvalch. Iiecision depends on hosl IioIog syslen (1 second oi
niIIiseconds).
/stop_stopwatch


Fernando Senz-Prez 166/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Slop slopvalch. Iiecision depends on hosl IioIog syslen (1 second oi
niIIiseconds).
/display_stopwatch
DispIay slopvalch. Iiecision depends on hosl IioIog syslen (1 second oi
niIIiseconds).
%.14.11 Im&lementor
/debug
LnalIe delugging in lhe hosl IioIog inleipielei
/indexing
DispIay vhelhei hash indexing on neno lalIes is enalIed
/indexing Switch
LnalIe oi disalIe hash indexing on neno lalIes (on oi off, iesp.) DefauIl is
enalIed, vhich shovs a nolicealIe speed-up gain in sone cases
/optimize_cc
DispIay vhelhei conpIele conpulalions oplinizalion is enalIed
/optimize_cc Switch
LnalIe oi disalIe conpIele conpulalions oplinizalion (on oi off, iesp. and
enalIed ly defauIl). Iixpoinl ileialions and/oi exlensionaI dalalase ieliievaIs
nighl leen saved
/optimize_ep
DispIay vhelhei exlensionaI piedicales oplinizalion is enalIed
/optimize_ep Switch
LnalIe oi disalIe exlensionaI piedicales oplinizalion (on oi off, iesp. and
enalIed ly defauIl). Iixpoinl ileialions and exlensionaI dalalase ieliievaIs aie
saved foi exlensionaI piedicales as a singIe Iineai felching is peifoined foi
conpuling lhen
/optimize_nrp
DispIay vhelhei non-iecuisive piedicales oplinizalion is enalIed
/optimize_nrp Switch
LnalIe oi disalIe non-iecuisive piedicales oplinizalion (on oi off, iesp. and
enalIed ly defauIl). Menoing is onIy peifoined foi lop-IeveI goaIs
/optimize_st
DispIay vhelhei slialun oplinizalion is enalIed
/optimize_st Switch
LnalIe oi disalIe slialun oplinizalion (on oi off, iesp. and enalIed ly
defauIl). LxlensionaI lalIe Iookups aie saved foi non-iecuisive piedicales
caIIing lo iecuisive ones, lul noie lupIes nighl le conpuled if lhe non-
iecuisive caII is fiIleied, as in lhis case an open caII is sulnilled inslead (i.e., nol
fiIleied)
/optimize_sn
DispIay vhelhei diffeienliaI seni-naive oplinizalion is enalIed


Fernando Senz-Prez 167/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

/optimize_sn Switch
LnalIe oi disalIe diffeienliaI seni-naive oplinizalion (on oi off, iesp. and
enalIed ly defauIl). Conpuling Iineai iecuisive piedicales saves ieusing lupIes
in oIdei fixpoinl ileialions.
/nospyall
Renove aII IioIog spy poinls in lhe hosl IioIog inleipielei. DisalIe delugging
/nospy SPred[/Arity]
Renove lhe spy poinl on lhe given piedicale in lhe hosl IioIog inleipielei
/spy Pred[/Arity]
Sel a spy poinl on lhe given piedicale in lhe hosl IioIog inleipielei
/system Goal
Sulnil Goal lo lhe undeiIying IioIog syslen
/terminate
Teininale lhe cuiienl DLS session vilhoul haIling lhe hosl IioIog syslen
%ynonym: /t.
/write String
Wiile String lo consoIe. String can conlain syslen vaiialIes as
$stopwatch$ (vhich hoIds lhe cuiienl slopvalch line) and
$total_elapsed_time$ (vhich hoIds lhe Iasl lolaI eIapsed line) (See
Sulseclion 5.14.11.1 foi syslen vaiialIes)
/writeln String
As /write lul adding a nev Iine al lhe end of lhe sliing
/write_to_file File String
Wiile String lo File. If File does nol exisl, il is ciealed, olheivise, pievious
conlenls aie nol deIeled and String is sinpIy appended lo File. String can
conlain syslen vaiialIes as $stopwatch$ (vhich hoIds lhe cuiienl slopvalch
line) and $total_elapsed_time$ (vhich hoIds lhe Iasl lolaI eIapsed line)
(See Sulseclion 5.14.11.1 foi syslen vaiialIes)
/writeln_to_file File
As /write_to_file lul viiling a nev Iine
%.14.11.1 System 0aria*les
The foIIoving aie lhe syslen vaiialIes vhich can le used vhen viiling sliings
lo eilhei lhe consoIe oi a fiIe vilh lhe connands write, writeln, write_to_file,
and writeln_to_file:
$computation_time$ Iasl eIapsed line due lo conpuling (eIiding paising
and dispIay line)
$display_time$ Iasl eIapsed line due lo dispIay (eIiding paising and
conpuling line)
$parsing_time$ Iasl eIapsed line due lo paising (eIiding conpuling and
dispIay line)
$stopwatch$ cuiienl slopvalch line
$last_stopwatch$ slopvalch line foi ils Iasl slop


Fernando Senz-Prez 168/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

$total_elapsed_time$ Iasl lolaI eIapsed line
In addilion, any dynanic piedicale of aiily 1 inpIenenled in IioIog. as
incIuded in souice fiIes can le accessed as a (iead-onIy) syslen vaiialIe The foIIoving
is a (possilIy non-updaled) Iisl of such piedicales (lhe fiIe des.pl conlains aII
decIaialions of such piedicales):
$optimize_cf$ IIag indicaling vhelhei conpIele fIag oplinizalion is
enalIed
$optimize_cc$ IIag indicaling vhelhei conpIele conpulalion oplinizalion
is enalIed
$optimize_ep$ IIag indicaling vhelhei exlensionaI piedicale oplinizalion is
enalIed
$optimize_nrp$ IIag indicaling vhelhei non-iecuisive piedicale
oplinizalion is enalIed
$optimize_st$ IIag indicaling vhelhei slialun oplinizalion is enalIed
$optimize_sn$ IIag indicaling vhelhei seni-naive diffeienliaI oplinizalion
is enalIed
$edb_retrievals$ IIag indicaling lhe nunlei of LD ieliievaIs duiing
fixpoinl conpulalion
$et_lookups$ IIag indicaling lhe nunlei of LT Iookups
$ct_lookups$ IIag indicaling lhe nunlei of CT Iookups
$cf_lookups$ IIag indicaling lhe nunlei of CI Iookups
$fp_iterations$ IIag indicaling lhe nunlei of ileialions duiing fixpoinl
conpulalion
$verbose$ Veilose node fIag
$pretty_print$ Iielly piinl foi Iislings (lakes noie Iines lo piinl)
$et_flag$ Lxlension TalIe fIag
$strata$ ResuIl fion a slialificalion
$pdg$ Iiedicale Dependency Ciaph
$user_predicates$ Lisl of usei piedicales
$recursive_predicates$ Lisl of iecuisive piedicales
$extensional_predicates$ Lisl of exlensionaI piedicales
$non_recursive_predicates$ Lisl of non-iecuisive piedicales
$nr_nd_predicates$ Lisl of non-iecuisive piedicales vhich do nol depend
on any iecuisive piedicales
$null_id$ Inlegei idenlifiei foi nuIIs, iepiesenled as '$NULL'(i), vheie 'i' is
lhe nuII idenlifiei
$rule_id$ Inlegei idenlifiei foi iuIes, iepiesenled as
dalaIog(RuIe,NVs,i,Lines,IiIeId,Kind), vheie 'i' is lhe iuIe idenlifiei


Fernando Senz-Prez 16/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

$duplicates$ IIag indicaling vhelhei dupIicales aie enalIed
$timing$ IIag indicaling eIapsed line dispIay: on, off oi delaiIed
$format_timing$ IIag indicaling vhelhei foinalling of line is enalIed oi
disalIed: on oi off
$safe$ IIag indicaling vhelhei piogian liansfoinalion foi safe iuIes is
aIIoved
$simplification$ IIag indicaling vhelhei piogian sinpIificalion foi
peifoinance is aIIoved
$language$ IIag indicaling lhe cuiienl defauIl queiy Ianguage
$start_path$ Ialh on fiisl iniliaIizalion
$development$ IIag indicaling a deveIopnenl session. Lislings and
consuIlings shov souice and conpiIed iuIes
$safety_warnings$ IIag indicaling vhelhei safely vainings aie enalIed
$last_autoview$ IIag indicaling lhe Iasl auloviev execuled. This auloviev
shouId le ieliacled upon exceplions
$current_db$ IIag indicaling lhe cuiienl opened D
$trusting$ IIag indicaling vhelhei a liusl fiIe is leing piocessed
$trusted_views$ Iiedicale conlaining liusled viev nanes
$output$ IIag indicaling vhelhei oulpul is enalIed (on oi off)
$check_ic$ IIag indicaling vhelhei inlegiily consliainl checking is enalIed
(on oi off)
$my_odbc_query_handle$ IIag indicaling lhe handIe lo lhe Iasl ODC
queiy
$compact_listings$ IIag indicaling vhelhei conpacl Iislings aie enalIed
$show_compilations$ IIag indicaling vhelhei SQL lo DL conpiIalions aie
dispIayed
$show_sql$ IIag indicaling vhelhei exleinaIIy-piocessed SQL slalenenls aie
dispIayed
$state$ Slales foi vaiious fIags lo le iesloied upon exceplions
$running_info$ IIag indicaling vhelhei iunning info is lo le dispIayed
(nunlei of consuIled iuIes)
$tapi$ IIag indicaling vhelhei a lapi connand is leing piocessed
$hypothetical$ IIag indicaling vhelhei hypolhelicaI queiies aie enalIed
(on oi off)
$indexing$ IIag indicaling vhelhei indexing on exlension lalIe is enalIed
(on oi off)
$computed_tuples% IIag vilh lhe nunlei of conpuled lupIes duiing
fixpoinl conpulalion (foi iunning info dispIay)


Fernando Senz-Prez 17!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

$display_answer$ IIag indicaling vhelhei ansveis aie lo le dispIayed
upon soIving (on oi off)
$display_nbr_of_tuples$ IIag indicaling vhelhei lhe nunlei of lupIes
aie lo le dispIayed upon soIving (on oi off)
$order_answer$ IIag indicaling vhelhei lhe ansvei is lo le dispIayed upon
soIving (on oi off)
$multiline$ IIag indicaling vhelhei nuIliIine inpul is enalIed (on oi off)
$my_statistics$ IIag foi slalislics
$host_statistics$ IIag foi hosl slalislics
$stopwatch$ IIag indicaling slopvalch eIapsed line
$des_sql_solving$ IIag indicaling vhelhei DLS soIving is foiced foi
exleinaI DMSs
$prompt$ IIag indicaling lhe pionpl foinal
$editor$ IIag indicaling lhe cuiienl exleinaI ediloi, if defined aIieady
$nulls$ IIag indicaling vhelhei nuIIs aie aIIoved
%.1% Ae)tual 2?I
Ralhei lhan pioviding a IioIog undeiIying syslen dependenl AII, DLS
piovides a lexluaI AII (TAII, TexluaI AppIicalion Iiogianning Inleiface) foi ils
connunicalion lo exleinaI appIicalions. Il can used via slandaid inpul and oulpul
slieans, as piovided ly lhe OS.
Such inleiface has leen guided ly lhe denands of lhe ACIDL CUI (CiaphicaI
Usei Inleiface) in oidei lo aIIov useis lo inleiacl vilh lhe syslen via a }ava
appIicalion. This vay, il is possilIe lo inspecl and nodify dalalase schena and lalIe
conlenls, lolh lhose nanaged ly DLS and aIso exleinaI dala souices as RDMS's,
spieadsheels oi csv pIain fiIes connecled ly an ODC conneclion. Hovevei, lhis TAII
can le used fion any appIicalion viole in any Ianguage and iunning on any pIalfoin,
piovided lhal il can handIe inpul and oulpul slandaid slieans.
SeveiaI exisling connands, slalenenls and queiies can le piocessed via lhis
inleiface. As veII, nev connands and slalenenls have leen added lo suppoil lhe CUI
iequiienenls desciiled alove. Inpul synlax is as foi DLS, vheieas ansveis foIIov a
conciele foinal foi easing lheii paising. Any inpul lo lhis inleiface nusl le piepended
ly lhe connand /tapi, and cannol le spiead leyond a singIe Iine, as shovn nexl:
Inpul: /tapi /test_tapi
Oulpul: $success
Nolice lhal aflei lhe connand /tapi, anolhei connand foIIovs:
/test_tapi, vhich is onIy inlended lo lesl vhelhei a successfuI conneclion lelveen
lhe exleinaI appIicalion and DLS can le eslalIished. If so, lhe ansvei $success is senl
lo lhe oulpul sliean. The usuaI DLS connand pionpl is nol senl, as veII as no exlia
lIank Iines (even if conpacl Iislings aie disalIed, cf. Seclion 5.14.1O). Any inpul aflei
/lapi can aIso le sulnilled in lhe DLS connand pionpl, lul foIIoving lhe usuaI DLS
oulpul, inslead of lhe TAII-oiienled vay.


Fernando Senz-Prez 171/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

A lypicaI scenaiio foi accessing DLS fion an exleinaI appIicalion is lo slail a
piocess fion lhis appIicalion and connecling adequaleIy inpul and oulpul slieans. If
iun on Windovs, use lhe consoIe appIicalion des.exe foi such piocess, olheivise,
use des (lolh piovided in lhe linaiy disliilulion foi youi conciele opeialing syslen).
%.1%.1 1otes a*out t/e Inter:ace
Texl in fonl Courier New aie foi lexluaI inpul and oulpul. Italized
Courier New sland foi inpul lhal lhe TAII usei nusl piovide vilh a conciele
inpul. Ioi exanpIe, desciiplion foi diopping a lalIe incIudes: /tapi drop
table table_name, vheie table_name is lhe pIacehoIdei foi youi conciele
lalIe lo le diopped.
Lines slailing vilh aie ienaiks vhich aie nol needed lo le incIuded (lhey
aie onIy foi expIanaloiy puiposes)
Types ieluined ly a dalalase oi piedicale handIed ly DLS incIude:
o string(varchar)
o string(varchar(N))
o string(char(N))
o number(integer)
o number(float)
Wheie N is an inlegei giealei lhan O.
Types ieluined ly ODC dalalases depend on lhe conciele exleinaI DMS.
Chaiaclei sliings as ieluined ly DLS aie encIosed lelveen singIe quoles. This
aIIovs in pailicuIai lo dislinguish lhese sliings fion lhe null vaIue, vhich can
occui in any dala lype.
DalaIog idenlifieis in TAII inpuls nusl le encIosed lelveen singIe quoles
shouId lhey conlain speciaI chaiacleis (as lIanks, connas and quoles). If an
idenlifiei conlains a singIe quole, lhis nusl le viillen lvice as, e.g.,
'pete''s' , vhich iepiesenls pete's
DDL (Dala Definilion Language) slalenenls foi SQL and DalaIog incIude:
o CREATE TABLE (SQL)
o CREATE VIEW (SQL)
o RENAME (SQL)
o :-strong_constraint (DalaIog)
DQL (Dala Queiy Language) SQL slalenenls incIude:
o SELECT
o WITH
Any inpul lo connand /tapi is piocessed as a DLS inpul. Hovevei, oulpul is
onIy foinalled foi lhose connands and queiies as Iisled in seclions 5.15.2 and
5.15.3. So, feeding unsuppoiled inpuls lo /tapi nighl pioduce unexpecled
iesuIls. Useis of TAII aie expecled lo ask foi olhei connands and/oi
slalenenls needed foi lheii conciele appIicalions. Ieedlack is veIcone.
%.1%.1.1 Identi:iers
As SQL idenlifieis can conlain speciaI chaiacleis vhich can le nissed vilh
olhei Ianguage consliuclois, lhey aie encIosed lelveen deIinileis in such a case. This
docunenl conlains an allievialed nolalion: name and column_name, foi lalIe and
vievs in lhe foinei, and coIunns in lhe second. When an SQL idenlifiei is viillen as
pail of a TAII inpul, lhey nusl le encIosed lelveen lhe chaiacleis L and R (Iefl and
iighl deIinileis, iespecliveIy). Chaiacleis foi such deIinileis depend on lhe exleinaI


Fernando Senz-Prez 172/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DMS. Ioi inslance, MS Access iequiies [ and ], iesp., lul slandaid SQL defines
doulIe quoles foi lolh (") (MS Access does nol suppoil lhis).
In oidei lo knov vhal aie such chaiacleis foi lhe cuiienl conneclion, one can
sulnil lhe foIIoving connands:

/tapi /sql_left_delimiter

/tapi /sql_right_delimiter
DalaIog idenlifieis suffei a siniIai silualion lul lhey nusl le encIosed, if
needed lecause conlaining speciaI chaiacleis, lelveen singIe quoles. Ioi exanpIe:

/tapi /listing 't'
DalaIog idenlifieis as ieluined ly DLS aie nol deIiniled, lhough.
%.1%.1.2 Finds o: 2ns3ers
Any inpul can ieluin eilhei a successfuI ansvei (vilh a synlax desciiled foi
each suppoiled connand and slalenenl) oi an eiioi. Theie aie seveiaI kinds of
ansveis:
Regular:
o SuccessfuI ansvei vilh no ieluin dala:
$success
o Liioi:
$error
code
text
...
text
$eot
Wheie code is lhe eiioi code and text is ils lexluaI desciiplion, vhich
can consisl of seveiaI Iines. Lasl Iine is lhe lexl foi denoling end of
liansnission. Liioi codes aie digils slailing ly eilhei O (denoling an
exceplion eiioi), oi 1 (denoling a vaining), oi 2 (denoling an exlended
infoinalive nessage).
Boolean:
OnIy one Iine, eilhei one of lhe foIIoving:
o $true
o $false
If an eiioi occuis, il is oulpul as in lhe ieguIai ansvei.
Defined specifically for a given command or statement.
If an eiioi occuis, il is oulpul as in lhe ieguIai ansvei.
%.1%.2 A2?IGena*led Commands
This seclion shovs each suppoiled connand foi TAII connunicalion.
Connand:
/tapi /sql_left_delimiter


Fernando Senz-Prez 173/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Ansvei:
OnIy one Iine vilh a singIe chaiaclei coiiesponding lo lhe SQL Iefl deIinilei as
defined ly lhe dalalase nanagei (eilhei DLS oi lhe exleinaI DMS via ODC).
LxanpIe assuning an ODC conneclion lo MS Access:
Inpul:
/tapi /sql_left_delimiter
Oulpul:
[

Connand:
/tapi /sql_right_delimiter
Ansvei:
OnIy one Iine vilh a singIe chaiaclei coiiesponding lo lhe SQL iighl deIinilei
as defined ly lhe dalalase nanagei (eilhei DLS oi lhe exleinaI DMS via
ODC).
LxanpIe assuning an ODC conneclion lo MS Access:
Inpul:
/tapi /sql_right_delimiter
Oulpul:
]

Connand:
/tapi /cd
Ansvei:
OnIy one Iine vilh lhe fuII palh DLS vas slailed fion.
LxanpIe:
Inpul:
/tapi /cd
Oulpul:
c:/des

Connand:
/tapi /cd Path
Ansvei:
OnIy one Iine vilh lhe fuII nev palh.
LxanpIe:
Inpul:
/tapi /cd examples
Oulpul:
c:/des/examples



Fernando Senz-Prez 174/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Connand:
/tapi /consult File
/tapi /c File
/tapi /[File]
Ansvei:
Infoinalion aloul lhe Ioaded piogian and a finaI Iine conlaining $eot.
LxanpIes:
Inpul:
/tapi /[family]
Oulpul:
Info: 11 rules consulted.
$eot

Inpul:
/tapi /c family,fact
Oulpul:
Warning: N > 0 may raise a computing exception if non-
ground at run-time.
Warning: N1 is N - 1 may raise a computing exception if
non-ground at run-time.
Warning: F is N * F1 may raise a computing exception if
non-ground at run-time.
Warning: Next rule is unsafe because of variable(s):
[F,N]
fac(N,F) :-
N > 0,
N1 is N - 1,
fac(N1,F1),
F is N * F1.
Info: 13 rules consulted.
$eot

Connand:
/tapi /reconsult Files
/tapi /r Files
/tapi /[+Files]
Ansvei:
Infoinalion aloul lhe Ioaded piogian and a finaI Iine conlaining $eot.
LxanpIe:
Inpul:
/tapi /[+family]
Oulpul:
Info: 11 rules consulted.
$eot

Connand:


Fernando Senz-Prez 175/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

/tapi /test_tapi
Ansvei:
Regular"
Renaiks:
This connand is used lo lesl lhe cuiienl conneclion.
LxanpIe:
Inpul:
/tapi /test_tapi
Oulpul:
$success

Connand:
/tapi /open_db db
Aigunenls:
db: Database connection name. Not delimited.
Ansvei:
Regular"
Renaiks:
This connand is used lo open an ODC conneclion (cf. Seclion 5.14.2).
LxanpIe:
Inpul:
/tapi /open_db test
Oulpul:
$success

Connand:
/tapi /close_db
Ansvei:
Regular"
Renaiks:
This connand is used lo cIose lhe cuiienl ODC conneclion (cf. Seclion 5.14.2).
LxanpIe:
Inpul:
/tapi /close_db
Oulpul:
$success

Connand:
/tapi /current_db
Ansvei:


Fernando Senz-Prez 176/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Tvo Iines: lhe fiisl one conlaining lhe cuiienl ODC conneclion nane and lhe
second one lhe exleinaI DMS (cf. Seclion 5.14.2).
Renaiks:
This connand is used lo gel lhe cuiienl ODC conneclion nane (cf. Seclion
5.14.2).
LxanpIe:
Inpul, assuning lhal lhe ODC conneclion test is aIieady opened:
/tapi /current_db
Oulpul:
test
access

Connand:
/tapi /relation_exists relation_name
Aigunenls:
relation_name: Relation (table, view or predicate) name, which must be
enclosed between delimiters if needed.
Ansvei:
,oolean"
Renaiks:
This connand ieluins $true if lhe given ieIalion exisls, and $false
olheivise.
LxanpIe:
Inpul:
/tapi /relation_exists "v"
Oulpul:
$true

Connand:
/tapi ddl_query
Ansvei:
Regular"
Renaiks:
This DDL slalenenl ieluins $success upon a successfuI piocessing.
LxanpIe:
Inpul:
/tapi create table [t]([a] int)
Oulpul:
$success

Connand:
/tapi /dependent_relations pattern


Fernando Senz-Prez 177/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Wheie pattern can le eilhei relation_name oi relation_name/arity,
vheie relation_name slands foi a ieIalion nane and arity foi ils aiily.

Ansvei:
relation_name
...
relation_name
$eot
Wheie relation_name slands foi ieIalion nanes.
Renaiks:
DispIay lhe nanes of ieIalions lhal diieclIy depend on lhe given ieIalion.
ReIalions aie ieluined aIphalelicaIIy soiled.
LxanpIe:
Inpul, consideiing lhal vievs z1 y z2 iefeience lalIe t:
/tapi /dependent_relations "t"
Oulpul:
z1
z2
$eot

Connand:
/tapi /list_table_schemas
Ansvei:
table_name(column_name:type,..., column_name:type)
table_name(column_name:type,..., column_name:type)
...
table_name(column_name:type,..., column_name:type)
$eot
Wheie table_name slands foi lalIe nanes, column_name is a coIunn nane,
type is lhe coIunn lype, and $eot is lhe end of lhe liansnission.
Renaiks:
Reluin lalIe schenas.
TalIes aie ieluined aIphalelicaIIy soiled.
LxanpIe:
Inpul:
/tapi /list_table_schemas
Oulpul:
t(a:number(integer))
$eot

Connand:
/tapi /list_view_schemas
Ansvei:
view(column_name:type,..., column_name:type)


Fernando Senz-Prez 178/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

view(column_name:type,..., column_name:type)
...
view(column_name:type,..., column_name:type)
$eot
Wheie view_name slands foi viev nanes, column_name is a coIunn nane,
type is lhe coIunn lype, and $eot is lhe end of lhe liansnission.
Renaiks:
Reluin viev schenas.
Vievs aie ieluined aIphalelicaIIy soiled.
LxanpIe:
Inpul:
/tapi /list_view_schemas
Oulpul:
v(a:number(integer),b:string(varchar(20)))
$eot

Connand:
/tapi /list_table_constraints table_name
Aigunenls:
table_name: Table name (enclosed between !" delimiters, if needed).
Ansvei:
NN
$
PK
$
CK
...
CK
$
FK
...
FK
$
FD
...
FD
$
IC
...
IC
$eot
Wheie $ is a deIinilei foi diffeienl kinds of inlegiily consliainls, NN is a singIe
Iine vilh lhe nanes of coIunns vilh exislency consliainl, PK is a singIe Iine
vilh lhe piinaiy key consliainl, CK aie candidale keys, FK aie foieign keys, FD
aie funclionaI dependencies, IC aie usei-defined inlegiily consliainls, and
$eot is lhe end of liansnission.
Renaiks:


Fernando Senz-Prez 17/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Lisl lalIe consliainls.
If lheie aie no consliainls of a given lype, no Iine is viillen.
LxanpIe:
Inpul:
/tapi /list_table_constraints "s"
Oulpul (no exislency consliainl, piinaiy key |b, no candidale key, foieign key
|s.[a] |t.[a], funclionaI dependency a b, and usei-defined inlegiily
consliainl :- t(X),s(X,X).):
$
b
$
$
s.[a] -> t.[a]
$
[a] -> [b]
$
:- t(X),s(X,X).
$eot

Connand:
/tapi /relation_schema relation_name
Aigunenls:
relation_name: Relation name (either a table or view), which must be
enclosed between !" delimiters if needed.
Ansvei:
relation_kind
relation_name
column_name
type
column_name
type
...
column_name
type
$eot
Renaiks:
Reluin ieIalion schena of relation_name. Iiisl Iine in lhe ansvei is lhe kind
of ieIalion (eilhei $table foi a lalIe oi $view foi a viev), foIIoved ly ils
nane in lhe second Iine. Nexl and successive paii of Iines conlain lhe coIunn
nane and coIunn lype.
LxanpIe:
Inpul:
/tapi /relation_schema "t"
Oulpul:
$table
t
a


Fernando Senz-Prez 18!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

number(integer)
$eot

Connand:
/tapi /drop_ic constraint
Aigunenls:
constraint: #onstraint following Datalog synta$ (cf. ection %.&.&'.().
Ansvei:
Regular"
LxanpIe:
Inpul:
/tapi /drop_ic :-pk('s',['b'])
Oulpul:
$success

Connand:
/tapi /dbschema view_name
Aigunenls:
view_name: )iew name as an !" identifier, which needs to be enclosed
between !" delimiters if needed.
Ansvei:
relation_kind
relation_name
column_name
type
...
column_name
type
$
SQL
...
SQL
$
Datalog
...
Datalog
$eot
Renaiks:
Iiisl Iine in lhe ansvei is lhe kind of ieIalion ($view), foIIoved ly ils nane in
lhe second Iine. Nexl and successive paii of Iines conlain lhe coIunn nane and
ils lype. Nexl Iines conlain lhe SQL definilion of lhe viev, slailing vilh a Iine
conlaining lhe deIinilei $. Nexl Iines conlain lhe DalaIog definilion of lhe viev,
slailing vilh a Iine conlaining lhe deIinilei $. IinaIIy, end of liansnission is
lhe Iasl Iine.
olh DalaIog and SQL oulpuls aie dispIayed depending on vhelhei pielly
piinl is disalIed oi nol (cf. Seclion 5.14.7), i.e., each slalenenl oi iuIe can le in a
singIe Iine oi nuIlipIe Iines.


Fernando Senz-Prez 181/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

LxanpIe:
Inpul:
/tapi /dbschema "v"
Oulpul:
$view
v
a
number(integer)
b
string(varchar(20))
$
SELECT ALL *
FROM (t
NATURAL INNER JOIN
s);
$
$eot

Connand:
/tapi /is_empty relation_name
Aigunenls:
relation_name: Relation name (either a table or a view), which must be
enclosed between !" delimiters if needed.
Ansvei:
,oolean"
Renaiks:
Reluin $true is ieIalion relation_name is enply (i.e., il conlains no lupIes in
ils neaning) and $false olheivise.
LxanpIe:
Inpul:
/tapi /is_empty "t"
Oulpul:
$false

%.1%.3 A2?IGena*led #ueries
This seclion shovs each suppoiled queiy foi TAII connunicalion.

Queiy:
/tapi sql_ddl_query
Wheie sql_ddl_query can le any SQL DDL queiy (cf. Seclion 4.2.4).
Ansvei:
Regular"
LxanpIes:


Fernando Senz-Prez 182/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Inpul:
/tapi create table t(a int)
Oulpul:
$success

Inpul:
/tapi rename table t to q
Oulpul:
$success

Queiy:
/tapi sql_dml_query
Wheie sql_dml_query can le any SQL DML queiy (cf. Seclion 4.2.5).
Ansvei:
If successfuI, one singIe Iine vilh lhe nunlei of affecled lupIes.
LxanpIes:
Inpul:
/tapi insert into [t] values(3)
Oulpul:
1

Inpul:
/tapi insert into [t] values('3')
Oulpul:
$error
0
Type mismatch [number(integer)] (table declaration)
$eot

Queiy:
/tapi sql_dql_query
Wheie sql_dql_query can le any SQL DQL queiy (cf. Seclion 4.2.6).
Ansvei:
relation_name
column_name
type
...
column_name
type
$
value
...
value
$
...
$


Fernando Senz-Prez 183/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

value
...
value
$eot
Wheie relation_name is lhe nane of lhe ansvei ieIalion, column_name is a
coIunn nane, type is lhe coIunn lype, value is lhe coIunn vaIue, $ is lhe iecoid
deIinilei and $eot is lhe end of lhe liansnission.
Renaiks:
This DQL slalenenl ieluins in lhe fiisl Iine lhe nane of lhe ansvei ieIalion, lhe
fiisl coIunn nane and ils lype in lhe nexl lvo Iines, and so foi aII of ils
coIunns. Then, each oi lhe lupIes in lhe ieIalion pieceded ly lhe iecoid
deIinilei ($). Lasl Iine is lhe end of liansnission.
LxanpIes:
Inpul, consideiing lhal lalIe s conlains lupIes |(1,'abc'), (null,'def'),
(null,null):
/tapi select * from [s]
Oulpul:
answer
s.a
number(integer)
s.b
string(varchar(20))
$
1
'abc'
$
null
'def'
$
null
null
$eot
Inpul, consideiing an enply lalIe s:
/tapi select * from [s]
Oulpul:
answer
s.a
number(integer)
s.b
string(varchar(20))
$eot
%.1" IS= Esca&e C/aracter Synta)
SpeciaI chaiacleis in conslanls and usei idenlifieis can le specified ly
piepending a lacksIash lo a escape-sequence. This fealuie depends on ils suppoil ly
lhe undeiIying IioIog syslen, so lhal lhe ieadei is iefeienced lo iead coiiesponding
enliy in lhe nanuaI of such syslen.


Fernando Senz-Prez 184/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

CuiienlIy, escape-sequences can onIy le specified in fiIes lo le consuIled, lul
nol al lhe connand pionpl.
Connon escape-sequences aie:
\a
AIain (ASCII chaiaclei code 7)
\l
ackspace (ASCII chaiaclei code 8)
\d
DeIele (ASCII chaiaclei code 127)
\e
Lscape (ASCII chaiaclei code 27)
\f
Ioin feed (ASCII chaiaclei code 12)
\n
Line feed/NevIine (ASCII chaiaclei code 1O)
\i
Caiiiage ieluin (ASCII chaiaclei code 13). Co lo lhe slail of lhe Iine,
vilhoul feeding a nev Iine
\l
HoiizonlaI lal (ASCII chaiaclei code 9)
\v
VeilicaI lal (ASCII chaiaclei code 11)
\xhex-digil...\
A chaiaclei code iepiesenled ly lhe hexadecinaI digils.
%.1( 1otes a*out t/e Im&lementation o: DES
DLS is inpIenenled vilh lhe oiiginaI ideas found in |Diel87, TS86, ID92j, lhal
deaI vilh leininalion issues of IioIog piogians. These ideas have leen aIieady used
in lhe deduclive dalalase connunily. Oui inpIenenlalion uses exlension lalIes foi
achieving a lop-dovn diiven lollon-up appioach. In ils cuiienl foin, il can le seen
as an exlension of lhe voik in |Diel87, ID92j in lhe sense lhal, in addilion, ve deaI
vilh negalion, undefined (aIlhough inconpIele) infoinalion, nuIIs and aggiegales,
aIso pioviding a noie efficienl lalIed nechanisn. AIso, lhe inpIenenlalion foIIovs a
diffeienl appioach: Inslead of liansIaling iuIes, ve inleipiel lhen.
DLS does nol pielend lo le an efficienl syslen lul a syslen capalIe of shoving
lhe nice aspecls of lhe noie poveifuI foin of Iogic ve can find in DalaIog syslens vil.
ieIalionaI dalalase syslens.


Fernando Senz-Prez 185/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

%.1(.1 Aa*ling
8

DLS uses an exlension lalIe vhich sloies ansveis lo goaIs pieviousIy
conpuled, as veII as lheii caIIs. Ioi lhe ease of lhe inlioduclion, ve assune an ansvei
lalIe and a caII lalIe lo sloie ansveis and caIIs, iespecliveIy. Ansveis nay le posilive
oi negalive, lhal is, if a caII lo a posilive goaI p succeeds, lhen lhe facl p is added as an
ansvei lo lhe ansvei lalIe, if a negaled goaI not(p) succeeds, lhen lhe facl not(p) is
added. CaIIs aie aIso added lo lhe caII lalIe vhenevei lhey aie soIved. This aIIovs us
lo delecl vhelhei a caII has leen pieviousIy soIved and ve can use lhe iesuIls in lhe
exlension lalIe (if any).
The aIgoiilhn vhich inpIenenls lhis idea is depicled nexl:

% Already called. Call table with an entry for the current call
memo(G) :-
build(G,Q), % Build in Q the same call with fresh variables
called(Q), % Look for a unifiable call in CT for the current call
subsumes(Q,G), % Test whether CT call subsumes the current call
!, %
et_lookup(G). % If so, use the results in answer table (ET)

% New call. Call table without an entry for the current call
memo(G) :-
assertz(called(G)), % Assert the current call to CT
( (et_lookup(G)) % First call returns all previous answers in ET
;
(solve_goal(G), % Solve the current call using applicable rules
build(G,Q), % Build in Q the same call with fresh variables
no_subsumed_by_et(Q), % Test whether there is no entry in ET for Q
et_assert(G), % If so, assert the current result in ET
et_changed)). % Flag the change
This aIgoiilhn, fiisl, lesls vhelhei lheie is a pievious caII lhal sulsunes

lhe
cuiienl caII. Theie aie lvo possiliIilies: 1) lheie is such a pievious caII: lhen, use lhe
iesuIl in lhe ansvei lalIe, if any. Il is possilIe lhal lheie is no such a iesuIl (foi
inslance, vhen conpuling lhe goaI p in lhe piogian p :- p) and ve cannol deiive
any infoinalion, 2) olheivise, piocess lhe nev caII knoving lhal lheie is no caII oi
ansvei lo lhis caII in lhe exlension lalIe. So, fiislIy sloie lhe cuiienl caII and lhen, soIve
lhe goaI vilh lhe piogian iuIes (iecuisiveIy appIying lhis aIgoiilhn). Once lhe goaI
has leen soIved (if succeeded), sloie lhe conpuled ansvei if lheie is no any pievious
ansvei sulsuning lhe cuiienl one (nole lhal, lhiough iecuision, ve can deIivei nev
ansveis foi lhe sane caII). This so-caIIed nenoizalion piocess is inpIenenled vilh
lhe piedicale memo/1 in lhe fiIe des.pl of lhe disliilulion, and viII aIso le iefeiied lo
as a neno funclion in lhe iesl of lhis nanuaI.
Negalive facls aie pioduced vhen a negalive goaI is pioved ly neans of
negalion as faiIuie (cIosed voiId assunplion). In lhis silualion, a goaI as not(p)

8
Ioi a conpIenenlaiy undeislanding of lhis seclion, lhe ieadei is advised lo iead
|Diel87j.

A lein T1 sulsunes a lein T2 if T1 is noie geneiaI lhan T2 and lolh leins aie
unifialIe. Lg: p(X,Y) sulsunes p(a,Z), p(X,Y) sulsunes p(U,V), p(X,Y) sulsunes
p(U,U), lul p(U,U) neilhei sulsunes p(a,b), noi p(X,Y).


Fernando Senz-Prez 186/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

vhich succeeds pioduces lhe facl not(p) vhich is added lo lhe ansvei lalIe, jusl lhe
sane as pioving a posilive goaI.
The connand /list_et shovs lhe cuiienl slale of lhe exlension lalIe, lolh
foi ansveis and caIIs aIieady ollained ly soIving one oi noie queiies (incidenlaIIy,
iecaII lhal you can focus on lhe conlenls of lhe exlension lalIe foi a given piedicale, cf.
Seclion 5.14.4). This connand is usefuI foi lhe usei vhen asking foi lhe neaning of
ieIalions, and foi lhe deveIopei foi exanining lhe Iasl caIIs leing peifoined. efoie
execuling any queiy, lhe exlension lalIe is enply, aflei execuling a queiy, al Ieasl lhe
caII is nol enply. AIso, lhe exlension lalIe is enply aflei lhe execulion of a lenpoiaiy
viev.
1!
The exlension lalIe conlains lhe caIIs nade duiing lhe Iasl fixpoinl ileialion
(see nexl seclion foi delaiIs), lhe caIIs aie cIeaied lefoie each ileialion vheieas lhe
ansveis aie kepl. The connand /clear_et cIeais lhe exlension lalIe conlenls, lolh
foi caIIs and ansveis.
%.1(.2 .i)&oint Com&utation
The lalIing nechanisn is insufficienl in ilseIf foi conpuling aII of lhe possilIe
ansveis lo a queiy. The ialionaIe lehind lhis cones fion lhe facl lhal lhe conpuled
infoinalion is nol conpIele vhen soIving a given goaI, lecause il can use inconpIele
infoinalion fion lhe goaIs in ils defining iuIes (lhese goaIs can le nuluaIIy iecuisive).
Theiefoie, ve have lo ensuie lhal ve pioduce aII lhe possilIe infoinalion ly finding a
fixpoinl of lhe neno funclion. The aIgoiilhn inpIenenling lhis is depicled nexl:

solve_star(Q,St) :-
repeat,
(remove_calls, % Clear CT
et_not_changed, % Flag ET as not changed
solve(Q,St), % Solve the call to Q using memoization at stratum St
fail % Request all alternatives
;
no_change, % If no more alternatives, start a new iteration
!, fail). % Otherwise, fail and exit
Iiisl, lhe caII lalIe is enplied in oidei lo aIIov lhe syslen lo liy lo ollain nev
ansveis foi a given caII, pieseiving lhe pievious conpuled ansveis. Then, lhe neno
funclion is appIied, possilIy pioviding nev ansveis. If lhe ansvei lalIe ienains lhe
sane as lefoie aflei lhis Iasl neno funclion appIicalion, ve aie done. Olheivise, lhe
neno funclion is ieappIied as nany lines as needed unliI ve find a slalIe ansvei
lalIe (vilh no changes in lhe ansvei lalIe). The ansvei lalIe conlains lhe slalIe nodeI
of lhe queiy (pIus peihaps olhei slalIe nodeIs foi lhe ieIalions used in lhe
conpulalion of lhe given queiy).
The fixpoinl is found in finile line lecause lhe neno funclion is nonolonic in
lhe sense lhal ve onIy add nev enliies each line il is caIIed vhiIe keeping lhe oId
ones. RepealedIy appIying lhe neno funclion lo lhe ansvei lalIe deIiveis a finile
ansvei lalIe since lhe nunlei of nev facls lhal can le deiived fion a DalaIog
piogian is finile (iecaII lhal lheie aie no conpound leins such as s
-
(z)). On lhe one
hand, lhe nunlei of posilive facls vhich can le infeiied aie finile lecause lheie is a
finile nunlei of giound facls vhich can le used in a given pioof, and pioofs have

1!
The conlenls of lhe exlension lalIe in lhis case shouId le iesloied inslead of leing
cIeaied, Iefl foi fuilhei inpiovenenls.


Fernando Senz-Prez 187/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

finile deplh piovided lhal lalIing pievenls ieconpulalions of oIdei nodes in lhe pioof
liee. On lhe olhei hand, lhe nunlei of negalive facls vhich can le infeiied is aIso
finile lecause lhey aie pioved using negalion as faiIuie. (IaiIuies aie aIvays finile
lecause lhey aie pioved liying lo gel a success.) IinaIIy, lheie aie facls lhal cannol le
pioved lo le liue oi faIse lecause of iecuision. These cases aie delecled ly lhe lalIing
nechanisn vhich pievenl infinile iecuision such as in p :- p.
Il is aIso possilIe lhal lolh a posilive and a negalive facl have leen infeiied foi
a given caII. Then, an undefined facl iepIaces lhe conliadicloiy infoinalion. The
inpIenenlalion sinpIy ienoves lhe conliadicloiy facls and infoins aloul lhe
undefinedness. As aIieady indicaled (see Seclion 6.8.1), lhe aIgoiilhn foi deleinining
undefinedness is inconpIele.
%.1(.3 De&endency !ra&/s and Strati:icationH 1egationI =uter BoinsI and
2ggregates
Lach line a piogian is consuIled oi nodified (i.e., via sulnilling a lenpoiaiy
viev oi changing lhe dalalase), a piedicale dependency giaph is luiIl |ZCI+97j. This
giaph shovs lhe dependencies, lhiough posilive and negalive alons, anong
piedicales in lhe piogian. AIso, a negalive dependency is added foi each oulei join
goaI and aggiegale goaI.
This dependency giaph is usefuI foi finding a slialificalion foi lhe piogian
|ZCI+97j. A slialificalion coIIecls piedicales inlo nunleied sliala (1..N). A lasic
lollon-up conpulalion vouId soIve aII of lhe piedicales in slialun 1, lhen 2, and so
on, unliI lhe neaning of lhe vhoIe piogian is found. Wilh oui appioach, ve onIy
iesoil lo conpule ly slialun vhen a negalive dependency occuis in lhe piedicale
dependency giaph iesliicled lo lhe queiy, neveilheIess, each piedicale lhal is acluaIIy
needed is soIved ly neans of lhe exlension lalIe nechanisn desciiled in lhe pievious
seclion. As a consequence, nany conpulalions aie avoided v.i.l. a nave lollon-up
inpIenenlalion. See aIso nexl seclion on oplinizalions.
Oulei join and aggiegale goaIs aie aIso coIIecled inlo sliala as if lhey veie
negalive alons in oidei lo have lheii ansvei sel conpIeleIy defined and lheiefoie
ensuie leininalion of lhe conpulalion aIgoiilhn in piesence of nuII vaIues (foi oulei
joins) and inconpIele sel of vaIues (foi aggiegales).
%.1(.4 =&timiJations
DLS is nol laigeled al peifoinance ly any neans: il is inpIenenled on lop of
IioIog, il uses lhe (sIovei in nosl syslens) IioIog dynanic dalalase, il does nol aIIov
usei-defined indexes, inpIenenled aIgoiilhns aie nol lhe lesl ones, seveiaI lasks aie
iedone spaiingIy (aIlhough lhey can le acluaIIy saved), and so on. Once lhal said,
lheie has leen sliII a ninoi ioon foi oplinizing peifoinance so lhal piojecls of lhe
size DLS is inlended foi can le successfuIIy achieved. eIov, ve Iisl sone of such
oplinizalions lhal can le enalIed oi disalIed al usei iequesl (lhis fealuie is noie
oiienled lo lhe syslen inpIenenlois foi knoving lhe inpacl on peifoinance of such
oplinizalions). Lach oplinizalion is Iisled in a sulseclion aIong vilh lhe connand
(lelveen liackels) lhal is used foi disalIing oi enalIing il (vilh lhe svilch off and
on, iespecliveIy).


Fernando Senz-Prez 188/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

%.1(.4.1 Com&lete Com&utations D/optimize_ccE
Lach caII duiing lhe conpulalion of a slialun (slialun saluialion) is
ienenleied in addilion lo ils oulcone (in lhe ansvei lalIe). Lven vhen lhe caIIs aie
ienoved in each fixpoinl ileialion (iecaII Seclion 5.17.2), nosl geneiaI ones do peisisl
as a coIIaleiaI dala sliucluie lo le used foi saving conpulalions shouId any of lhen is
caIIed again duiing eilhei conpuling a highei slialun oi a sulsequenl queiy soIving.
'cc' slands foi conpIeled conpulalion, so lhal if a caII is naiked as a conpIeled
conpulalion, il is nol even liied if caIIed again. This neans lhe foIIoving lvo poinls: 1)
Duiing lhe conpulalion of lhe neno funclion, caIIs aIieady conpuled aie nol liied lo
le soIved again, and onIy lhe enliies in lhe neno lalIe aie ieluined. 2) Moieovei,
conpuling lhe neno funclion is conpIeleIy avoided if a sulsuning aIieady-conpuled
caII can le found. In lhe fiisl case, lhal saves soIving goaIs in conpuling lhe neno
funclion. In lhe second case, lhal conpIeleIy saves fixpoinl conpulalion.
The foIIoving syslen session shovs hov lhis oplinizalion voiks. Iiisl, ve
enalIe slalislics coIIeclion, enalIe veilose oulpul lo aulonalicaIIy dispIay slalislics
iesuIls, disalIe aII lhe oplinizalions, asseil lhe facl p(1) and sulnil lhe queiy p(X):

DES> /statistics on
DES> /verbose on
DES> /optimize_cc off
Info: Complete computations optimization is off.
DES> /optimize_ep off
Info: Extensional predicate optimization is off.
DES> /optimize_nrp off
Info: Non-recursive predicates optimization is off.
DES> /optimize_st off
Info: Stratum optimization is already disabled.
DES> /optimize_sn off
Info: Differential semi-naive optimization is already disabled.
DES> /assert p(1)
Info: Computing predicate dependency graph...
Info: Computing strata...
Info: Rule asserted.
DES> p(X)
Info: Parsing query...
Info: Query successfully parsed.
Info: Solving query p(X)...
Info: Displaying query answer...
Info: Sorting answer...
{
p(1)
}
Info: 1 tuple computed.
Info: Fixpoint iterations: 2
Info: EDB retrievals : 2
Info: IDB retrievals : 0
Info: ET retrievals : 4
Info: ET look-ups : 6
Info: CT look-ups : 2
Info: CF look-ups : 0


Fernando Senz-Prez 18/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

As lhe slalislics shov, 2 fixpoinl ileialions have leen needed lo deduce lhe
oulpul. In lhe fiisl one, lhe iuIe p(1) is iead foi lhe fiisl line. Then, in lhe second
ileialion, il is iead again and as lhe ansvei lalIe has nol changed, lhen lhis neans lhal
lhe fixpoinl has leen ieached. The dispIay "LD ieliievaIs" shovs lhose lvo facl ieads
(LD slands foi LxlensionaI Dalalase).
If lhe sane queiy is sulnilled again:

DES> p(X)
Info: Parsing query...
Info: Query successfully parsed.
Info: Solving query p(X)...
Info: Displaying query answer...
Info: Sorting answer...
{
p(1)
}
Info: 1 tuple computed.
Info: Fixpoint iterations: 1
Info: EDB retrievals : 1
Info: IDB retrievals : 0
Info: ET retrievals : 4
Info: ET look-ups : 4
Info: CT look-ups : 1
Info: CF look-ups : 0
lhen onIy 1 ileialion is needed lo ieach lhe fixpoinl, and onIy one LD ieliievaI is
done, as lhe ansvei lalIe conlained an enliy foi p(1) aIieady foi lhe sane caII. This
iIIusliales poinl 1 alove.
Nov Iel's enalIe lhe oplinizalion, pieviousIy deIeling lhe conlenls of lhe
ansvei lalIe so lhal ve aie in lhe sane slailing silualion again:

DES> /clear_et
Info: Extension table cleared.
DES> /optimize_cc on
Info: Complete flag optimization is on.
DES> p(X)
Info: Parsing query...
Info: Query successfully parsed.
Info: Solving query p(X)...
Info: Displaying query answer...
Info: Sorting answer...
{
p(1)
}
Info: 1 tuple computed.
Info: Fixpoint iterations: 2
Info: EDB retrievals : 2
Info: IDB retrievals : 0
Info: ET retrievals : 4
Info: ET look-ups : 6
Info: CT look-ups : 2
Info: CF look-ups : 1


Fernando Senz-Prez 1!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

As lefoie, 2 fixpoinl ileialions and 2 LD ieliievaIs aie needed. ul, if ve
sulnil again lhe queiy:

DES> p(X)
Info: Parsing query...
Info: Query successfully parsed.
Info: Solving query p(X)...
Info: Displaying query answer...
Info: Sorting answer...
{
p(1)
}
Info: 1 tuple computed.
Info: Fixpoint iterations: 0
Info: EDB retrievals : 0
Info: IDB retrievals : 0
Info: ET retrievals : 2
Info: ET look-ups : 2
Info: CT look-ups : 0
Info: CF look-ups : 1
lhen, as lhe conpulalion foi lhe goaI p(X) is conpIele, lhen no fixpoinl ileialions aie
needed. Ioi lhe sane ieason, no LD ieliievaIs aie needed, as jusl lhe conlenls of lhe
neno lalIe aie ieluined. This iIIusliales poinl 2 alove.
%.1(.4.2 E)tensional ?redicates D/optimize_epE
LxlensionaI piedicales aie nol needed lo le ileialiveIy conpuled. So, no
fixpoinl conpulalion is needed foi lhen. They aie knovn fion lhe piedicale
dependency giaph sinpIy lecause lhey occui in lhe giaph vilhoul inconing aics. Ioi
lhen, a Iineai felching is enough lo deiive lheii neanings. 'ep' slands foi 'exlensionaI
piedicales'.
In lhe foIIoving syslen session ve iIIusliale lhis vilh lhe facl p(1):

DES> p(X)
Info: Parsing query...
Info: Query successfully parsed.
Info: Solving query p(X)...
Info: Displaying query answer...
Info: Sorting answer...
{
p(1)
}
Info: 1 tuple computed.
Info: Fixpoint iterations: 1
Info: EDB retrievals : 1
Info: IDB retrievals : 0
Info: ET retrievals : 2
Info: ET look-ups : 3
Info: CT look-ups : 0
Info: CF look-ups : 0
vheie lheie aie 1 fixpoinl ileialion and onIy one LD ieliievaI. This oplinizalion is
independenl fion lhe conpIeled conpulalions oplinizalion.


Fernando Senz-Prez 11/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Successive caIIs viII iendei lhe sane lehavioi, unIess lhe conpIele
conpulalions oplinizalion is enalIed:

DES> p(X)
Info: Parsing query...
Info: Query successfully parsed.
Info: Solving query p(X)...
Info: Displaying query answer...
Info: Sorting answer...
{
p(1)
}
Info: 1 tuple computed.
Info: Fixpoint iterations: 0
Info: EDB retrievals : 0
Info: IDB retrievals : 0
Info: ET retrievals : 2
Info: ET look-ups : 2
Info: CT look-ups : 0
Info: CF look-ups : 1
vheie no fixpoinl ileialions and no LD ieliievaIs aie needed.
%.1(.4.4 1onGrecursi0e ?redicates D/optimize_nrpE
Lach non-iecuisive piedicale can le exliacled oul fion lhe fixpoinl ileialive
cycIe lecause ils neaning can le conpuled ly iequesling aII ils soIulions al once.
Iuilhei fixpoinl ileialions von'l deveIop nev lupIes, so lhis vouId le useIess. In facl,
lhis is liue foi each non-iecuisive iuIe of a given piedicale. Though, lhis oplinizalion
is nol avaiIalIe yel.
The foIIoving exanpIe shovs lhe piedicale p as conposed of a facl and a iuIe.
Iiisl, il is conpuled vilh aII oplinizalions disalIed:

DES> /assert p(1)
DES> /assert p(X):-X=1+1
DES> p(X)
{
p(1),
p(2)
}
Info: 2 tuples computed.
Info: Fixpoint iterations: 2
Info: EDB retrievals : 2
Info: IDB retrievals : 2
Info: ET retrievals : 8
Info: ET look-ups : 8
Info: CT look-ups : 2
Info: CF look-ups : 0
Then, enalIing non-iecuisive piedicales oplinizalion and sulnilling lhe sane
queiy:

DES> /optimize_nrp on
Info: Non-recursive predicates optimization is on.
DES> /clear_et


Fernando Senz-Prez 12/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> p(X)
{
p(1),
p(2)
}
Info: 2 tuples computed.
Info: Fixpoint iterations: 1
Info: EDB retrievals : 1
Info: IDB retrievals : 1
Info: ET retrievals : 4
Info: ET look-ups : 4
Info: CT look-ups : 0
Info: CF look-ups : 0
In onIy one fixpoinl ileialion lhe neaning is conpuled foi vhich 1 LD and 1
ID ieliievaIs aie needed (lhe facl and iuIe, iespecliveIy).
%.1(.4.% Stratum D/optimize_stE
A piedicales vhich conlain no iecuisive iuIes lul caIIs lo iecuisive piedicales
do nol need lo le conpuled in lhe sane ileialive fixpoinl conpulalion. If lhis
oplinizalion is enalIed, such piedicales aie isoIaled fion iecuisive ones in anolhei
slialun, so lhal ileialive cycIes aie saved foi lhen. This silualion occuis, foi inslance,
vhen conpiIing SQL queiies lo DalaIog, as lhe inleinediale ieIalion answer is
inlioduced. Nexl syslen session iIIusliales lhis:

DES> :-type(p(a:int))
DES> /display_answer off
DES> /display_nbr_of_tuples off
DES> /timing on
DES> /assert p(1)
DES> /assert p(X):-p(Y),X=Y+1,Y<500
DES> select * from p
Info: Solving query answer(A)...
answer(p.a:number(integer)) ->
Info: Fixpoint iterations: 500
Info: EDB retrievals : 500
Info: IDB retrievals : 1000
Info: ET retrievals : 627246
Info: ET look-ups : 252999
Info: CT look-ups : 1500
Info: CF look-ups : 0
Info: Total elapsed time: 02.755 s.

DES> /optimize_st on
DES> select * from p
Info: Solving query answer(A)...
Info: Computing by stratum of [p(A)].
answer(p.a:number(integer)) ->
Info: Fixpoint iterations: 2
Info: EDB retrievals : 502
Info: IDB retrievals : 504
Info: ET retrievals : 381248
Info: ET look-ups : 128757
Info: CT look-ups : 1006


Fernando Senz-Prez 13/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Info: CF look-ups : 0
Info: Total elapsed time: 01.888 s.
Wilh lhis oplinizalion enalIed, Iess exlension lalIe Iookups aie needed and lhe
iesuIl is lheiefoie conpuled faslei. Hovevei, nole lhal non-leininalion nighl iaise
vhen lieaking sliala if using lhe nelapiedicale top: This is lecause top iequiies lhe
anounl of lupIes as indicaled fion ils goaI aigunenl. If lhis goaI is isoIaled in a highei
slialun, no lop consliainl is piopagaled lo lhe Iovei slialun, as in:

DES> :- type(p(a:int))
DES> /assert p(1)
DES> /assert p(X):-p(Y),X=Y+1
DES> select top 2 * from p
answer(p.a:number(integer)) ->
{
answer(1),
answer(2)
}
Info: 2 tuples computed.
DES> /optimize_st on
DES> select top 2 * from p
... non-terminating query
Thal is, as lhe SQL queiy has leen conpiIed lo:

answer(A) :-
top(10,p(A)).
lhen, piedicale answer/1 is Iocaled al slialun 2 and piedicale p/1 al slialun 1:

DES> /strata
[(p/1,1),(answer/1,2)]
and DLS liies lo soIve fiisl lhe goaI p(X) (nol top(10,p(A)))
11
vhich pioves lo le
non-leininaling as lheie is no lop consliainl on p. Iuilhei ieIeases nighl cope vilh
lhis issue.
%.1(.% Inde)ing D/indexingE
Theie is no piovision foi usei indexes up lo nov. Hovevei, indexing on neno
lalIes can le enalIed oi disalIed al usei iequesl. Theie aie lhiee lalIes vhich aie
indexed: lhe ansvei lalIe, lhe caII lalIe, and lhe conpIele conpulalion lalIe. The fiisl
one sloies lhe conpuled iesuIls foi lhe caIIs duiing queiy soIving and il is used in lhe
lalIing schene foi avoiding lo ieconpule aIieady knovn goaIs. The second one sloies
lhe caIIs so lhal il is possilIe lo knov vhelhei a sulsuning caII has leen done aIieady.
The lhiid lalIe sloies foi each caII vhelhei ils conpulalion has leen eilhei conpIeled
oi nol.
The nexl syslen session shovs a speed-up of aInosl 3 vhen enalIing
indexing.


11
And secondIy il vouId liy lhe goaI answer(X), aIlhough in lhis case il is unalIe
lecause of lhe non-leininaling fiisl goaI.


Fernando Senz-Prez 14/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

DES> /timing on
DES> /indexing off
DES> /pretty_print off
DES> /display_answer off
DES> p(X):-X=1;p(Y),Y<500,X=Y+1
Info: Processing:
p(X)
in the program context of the exploded query:
p(X) :- X=1.
p(X) :- p(Y),Y<500,X=Y+1.
Info: 500 tuples computed.
Info: Total elapsed time: 03.540 s.
DES> p(X):-X=1;p(Y),Y<500,X=Y+1
Info: Processing:
p(X)
in the program context of the exploded query:
p(X) :- X=1.
p(X) :- p(Y),Y<500,X=Y+1.
Info: 500 tuples computed.
Info: Total elapsed time: 01.279 s.
%.1(." ?orting to Unsu&&orted Systems
DLS is inpIenenled vilh seveiaI IioIog fiIes: des.pl, des_dcg.pl,
des_sql.pl, des_ra.pl, des_sql_debug.pl, des_dl_debug.pl,
des_types.pl, des_tc.pl, and des_glue.pl. The fiisl fiIe conlains lhe connon
piedicales foi aII of lhe pIalfoins (lolh IioIog inleipieleis and opeialing syslens)
foIIoving lhe IioIog ISO slandaid. IiIe des_dcg.pl, conlains lhe definilion of DCC
expansion (vhich vaiies fion one syslen lo anolhei). IiIes des_sql.pl and
des_ra.pl conlain lhe SQL and RA piocessoi, iespecliveIy. IiIes
des_sql_debug.pl and des_dl_debug.pl conlain lhe SQL and DalaIog
decIaialive deluggeis. IiIe des_types.pl, conlains lhe lype checking and infeience
syslen. IiIe des_tc.pl conlains lhe SQL lesl case geneialoi code. The Iasl fiIe
des_glue.pl conlains IioIog syslen specific code, vhich vaiy fion a syslen lo
anolhei. Adapling lhe piedicales found lheie shouId nol pose piolIens, piovided lhal
lhe IioIog inleipielei and opeialing syslen fealuie sone lasic chaiacleiislics (nainIy
aloul lhe fiIe syslen connands). In pailicuIai, finile donain consliainls is a nusl foi
suppoiling seveiaI fealuies of DLS, such as lype infeience and lesl case geneialion. If
you pIan lo poil DLS lo olhei syslens nol desciiled heie, you viII have lo nodify lhe
syslen specific IioIog fiIe lo suil youi syslen. If so, and if you vanl lo figuie as one of
lhe syslen conliilulois, pIease send an e-naiI nessage vilh lhe code and iefeience
infoinalion lo: fernan@sip.ucm.es, accepling lhal youi conliilulion viII le undei
lhe CNU Lessei CeneiaI IulIic License. (See lhe appendix foi delaiIs.)
". E)am&les
The DLS disliilulion conlains lhe diiecloiy examples vhich shovs seveiaI
fealuies of lhe syslen. UnIess expIicilIy noled, aII queiies have leen soIved aflei lhe
connands /verbose off and /pretty_print off have leen execuled.


Fernando Senz-Prez 15/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

".1 +elational =&erations D:iles relop.{dl,sql,ra}E
The piogian relop.dl is inlended lo shov hov lo ninic vilh DalaIog iuIes
lhe lasic ieIalionaI opeialions lhal can le found in lhe fiIe relop.sql. Il conlains
lhiee ieIalions (a, b, and c), vhich aie used as aigunenls of ieIalionaI opeialions. In
oidei lo have Ioaded lhis piogian and le alIe lo sulnil queiies you can consuIl il
vilh /c relop. In lhe ienaiks leIov, ieIalionaI opeialoi synloIs aie iepiesenled
vilh ASCII chaiacleis, as =|x| lo denole lhe Iefl oulei join , lhe Iellei x lo sinpIy
denole lhe Cailesian pioducl, and lhe Iellei U foi lhe sel union.

% (Extended) Relational Algebra Operations

% pi(X)(c(X,Y)) : Projection of the first argument of c
projection(X) :- c(X,Y).

% sigma(X=a2)(a) : Selecting tuples from a such that its first
argument is a2
selection(X) :- a(X), X=a2.

% a x b : Cartesian product of relations a and b
cartesian(X,Y) :- a(X), b(Y).

% a |x| b : Natural inner join of relations a and b
inner_join(X) :- a(X), b(X).

% a =|x| b : Left outer join of relations a and b
left_join(X,Y) :- lj(a(X), b(Y), X=Y).

% a |x|= b : Right outer join of relations a and b
right_join(X,Y) :- rj(a(X), b(Y), X=Y).

% a =|x|= b : Full outer join of relations a and b
full_join(X,Y) :- fj(a(X), b(Y), X=Y).

% a U b : Set union of relations a and b
union(X) :- a(X) ; b(X).

% a - b: Set difference of relations a and b
difference(X) :- a(X), not(b(X)).
Once lhe piogian is consuIled, you can queiy il ly, foi exanpIe:

DES> projection(X)
{
projection(a1),
projection(a2)
}
Info: 2 tuples computed.
The iesuIl of a queiy is lhe neaning of lhe viev, i.e., lhe facl sel foi lhe queiy
deiived fion lhe piogian vhelhei inlensionaIIy oi exlensionaIIy. In lhe alove
exanpIe, projection(X) coiiesponds lo lhe piojeclion of lhe fiisl aigunenl of
ieIalion c.


Fernando Senz-Prez 16/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The second viev in Seclion 4.1.5 ieluins:

Info: Processing:
a(X) :- b(X).
{
a(a1),
a(a2),
a(a3),
a(b1),
a(b2)
}
Info: 5 tuples computed.
Ioi aloIishing lhis piogian and execule lhe SQL slalenenls in relop.sql,
you can lype /abolish and /process relop.sql. Nole lhal lhe exlension can le
onilled in lhe process connand.
Heie, ve depail fion lhe DalaIog inleipielei and, if you aie lo sulnil SQL
queiies, il is usefuI lo svilch lo lhe SQL inleipielei via lhe connand /sql as inpuls
viII le paised onIy ly lhe SQL paisei. Olheivise, il viII le liied lo le idenlified as a
DalaIog inpul, and lhen as an SQL inpul.
Nole lhal in lhe fiIe relop.sql Iisled leIov, sliings aie encIosed lelveen
aposliophes. This is nol needed in lhe DalaIog Ianguage. In oidei lo execule lhe
conlenls of lhis fiIe, lype /process relop.sql.

% Switch to SQL interpreter
/sql
% Creating tables
create or replace table a(a);
create or replace table b(b);
create or replace table c(a,b);
% Listing the database schema
/dbschema
% Inserting values into tables
insert into a values ('a1');
insert into a values ('a2');
insert into a values ('a3');
insert into b values ('b1');
insert into b values ('b2');
insert into b values ('a1');
insert into c values ('a1','b2');
insert into c values ('a1','a1');
insert into c values ('a2','b2');
% Testing the just inserted values
select * from a;
select * from b;
select * from c;
% Projection
select a from c;
% Selection
select a from a where a='a2';
% Cartesian product
select * from a,b;


Fernando Senz-Prez 17/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

% Inner Join
select a from a inner join b on a.a=b.b;
% Left Join
select * from a left join b on a.a=b.b;
% Right Join
select * from a right join b on a.a=b.b;
% Full Join
select * from a full join b on a.a=b.b;
% Union
select * from a union select * from b;
% Difference
select * from a except select * from b;
If ve have ciealed lhe ieIalions in DalaIog, ve cannol access lhen fion SQL
unIess lhey had leen eilhei defined as lalIes oi vievs oi decIaied vilh lypes. Ioi
exanpIe, foIIoving lhe fiisl aIleinalive and aflei consuIling lhe fiIe relop.dl, ve can
sulnil:

create table a(a varchar);
And, lhen, accessing vilh an SQL slalenenl lhe lupIes lhal veie asseiled in
DalaIog:

DES-SQL> select * from a;
answer(a.a) ->
{
answer(a1),
answer(a2),
answer(a3)
}
Info: 3 tuples computed.
Olheivise, an eiioi is sulnilled:

Error: Unknown table or view "a"
IoIIoving lhe second aIleinalive and aflei consuIling lhe fiIe relop.dl, ve
can decIaie lypes foi a:

DES-SQL> /datalog :-type(a,[a:varchar])
DES-SQL> select * from a
answer(a.a) ->
{
answer(a1),
answer(a2),
answer(a3)
}
Info: 3 tuples computed.


Fernando Senz-Prez 18/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

".2 ?at/s in a !ra&/ D:iles paths.{dl,sql,ra}E
This piogian
12
inlioduces lhe use of iecuision in DLS ly defining lhe giaph in
Iiguie 1 and lhe sel of lupIes <oiigin, deslinalion> such lhal lheie is a palh fion oiigin
lo deslinalion.

b
c
a d

Iiguie 1. Ialhs in a Ciaph
The fiIe paths.dl conlains lhe foIIoving DalaIog code, vhich can le consuIled
vilh /c paths:

% Paths in a Graph

edge(a,b).
edge(a,c).
edge(b,a).
edge(b,d).

path(X,Y) :- path(X,Z), edge(Z,Y).
path(X,Y) :- edge(X,Y).
The queiy path(X,Y) yieIds lhe foIIoving ansvei:
{
path(a,a),
path(a,b),
path(a,c),
path(a,d),
path(b,a),
path(b,b),
path(b,c),
path(b,d)
}
Info: 8 tuples computed.
The fiIe paths.sql conlains lhe SQL counleipail code, vhich can le execuled
vilh /process paths.sql:

create table edge(origin,destination);
insert into edge values('a','b');
insert into edge values('a','c');
insert into edge values('b','a');
insert into edge values('b','d');
create view paths(origin,destination) as
with
recursive path(origin,destination) as

12
Adapled fion |TS86j.


Fernando Senz-Prez 1/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

(select * from edge)
union
(select path.origin,edge.destination
from path,edge
where path.destination =edge.origin)
select * from path;
So, you can gel lhe sane ansvei as lefoie vilh lhe SQL slalenenl:

DES-SQL> select * from paths;
answer(paths.origin, paths.destination) ->
{
answer(a,a),
answer(a,b),
answer(a,c),
answer(a,d),
answer(b,a),
answer(b,b),
answer(b,c),
answer(b,d)
}
Info: 8 tuples computed.
Anolhei shoilei foinuIalion is aIIoved in DLS vilh lhe foIIoving viev
definilion:

create view path(origin,destination) as
select * from
(select * from edge)
union
(select path.origin,edge.destination
from path,edge
where path.destination=edge.origin)
You can finaIIy conpaie lhis vilh lhe RA foinuIalion:

paths(origin,destination) :=
select true (edge)
union
project paths.origin,edge.destination
(edge zjoin paths.destination=edge.origin paths);

".3 S/ortest ?at/s D:ile spaths.{dl,sql,ra}E
Thanks lo aggiegale piedicales, one can code lhe foIIoving veision of lhe
shoilesl palhs piolIen (fiIe spaths.dl), vhich uses lhe sane definilion of edge as lhe
pievious exanpIe:

path(X,Y,1) :-
edge(X,Y).
path(X,Y,L) :-
path(X,Z,L0),
edge(Z,Y),
count(edge(A,B),Max),


Fernando Senz-Prez 2!!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

L0<Max,
L is L0+1.

sp(X,Y,L) :-
min(path(X,Y,Z),Z,L).
Nole lhal lhe infinile conpulalion lhal nay iaise fion using lhe luiIl-in is/2 is
avoided ly Iiniling lhe lolaI Ienglh of a palh lo lhe nunlei of edges in lhe giaph.
The foIIoving queiy ieluins aII lhe possilIe palhs and lheii coiiesponding
nininaI dislances:

DES> sp(X,Y,L)
{
sp(a,a,2),
sp(a,b,1),
sp(a,c,1),
sp(a,d,2),
sp(b,a,1),
sp(b,b,2),
sp(b,c,2),
sp(b,d,1)
}
Info: 8 tuples computed.
eIov is lhe SQL foinuIalion foi lhe sane piolIen (fiIe spaths.sql) :

DES-SQL> create or replace view
spaths(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;

DES-SQL> select * from spaths
answer(spaths.origin, spaths.destination, spaths.length) ->
{
answer(a,a,2),
answer(a,b,1),
answer(a,c,1),
answer(a,d,2),
answer(b,a,1),
answer(b,b,2),
answer(b,c,2),
answer(b,d,1)
}
Info: 8 tuples computed.
A possilIe RA foinuIalion foIIovs:

max_length(max_length) :=


Fernando Senz-Prez 2!1/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

group_by [] count(*) true (edge);

path(origin,destination,length) :=
project origin,destination,1 (edge)
union
project path.origin,edge.destination,path.length+1
(
path
zjoin path.destination=edge.origin and
path.length<max_length
(edge product max_length)
);

spaths(origin,destination,length) :=
group_by origin,destination origin,destination,min(length)
true
(path);
And ils queiy:

/ra select true (spaths);
".4 .amily Aree D:iles family.{dl,sql,ra}E
This (yel anolhei cIassic) piogian defines lhe faniIy liee shovn in Iiguie 2, lhe
sel of lupIes <parent,child> such lhal parent is a paienl of child (lhe ieIalion
parent), lhe sel of lupIes <ancestor,descendant> such lhal ancestor is an
ancesloi of descendant (lhe ieIalion ancestor), lhe sel of lupIes <father,child>
such lhal father is lhe falhei of child (lhe ieIalion father), and lhe sel of lupIes
<mother,child> such lhal mother is lhe nolhei of child (lhe ieIalion mother).

amy
t om
grace
fr ed
*ac+
car ol,,,
car ol,,
t ony
car ol,

Iiguie 2. IaniIy Tiee
The fiIe family.dl conlains lhe foIIoving DalaIog code, vhich can le
consuIled vilh /c family:

father(tom,amy).
father(jack,fred).
father(tony,carolII).
father(fred,carolIII).
mother(grace,amy).
mother(amy,fred).


Fernando Senz-Prez 2!2/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

mother(carolI,carolII).
mother(carolII,carolIII).

parent(X,Y) :- father(X,Y).
parent(X,Y) :- mother(X,Y).

ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y).
The queiy ancestor(tom,X) yieIds lhe foIIoving ansvei (lhal is, il conpules
lhe sel of descendanls of tom):
{
ancestor(tom,amy),
ancestor(tom,carolIII),
ancestor(tom,fred)
}
Info: 3 tuples computed.
SoIving lhe viev:

son(S,F,M) :- father(F,S),mother(M,S).
yieIds lhe foIIoving ansvei, conpuling lhe sel of sons:
Info: Processing:
son(S,F,M) :- father(F,S),mother(M,S).
{
son(amy,tom,grace),
son(carolII,tony,carolI),
son(carolIII,fred,carolII),
son(fred,jack,amy)
}
Info: 4 tuples computed.
The fiIe family.sql conlains lhe SQL counleipail code, vhich can le
execuled vilh /process family.sql:

create table father(father,child);
insert into father values('tom','amy');
insert into father values('jack','fred');
insert into father values('tony','carolII');
insert into father values('fred','carolIII');
create table mother(mother,child);
insert into mother values('grace','amy');
insert into mother values('amy','fred');
insert into mother values('carolI','carolII');
insert into mother values('carolII','carolIII');
create view parent(parent,child) as
select * from father
union
select * from mother;
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;


Fernando Senz-Prez 2!3/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The lvo exanpIe queiies alove can le foinuIaled in SQL as:

select * from ancestor where ancestor='tom';

select child,father,mother
from father,mother
where father.child=mother.child;
And aIso as RA queiies as:

/ra select ancestor='tom' (ancestor);

project child,father,mother
(father zjoin father.child=mother.child mother);
".% 4asic +ecursion ?ro*lem D:ile recursion.dlE
This exanpIe is inlended lo shov lhal queiies invoIving iecuisive piedicales do
leininale lhanks lo DLS fixpoinl soIving, ly conliasl vilh IioIogs usuaI SLD
iesoIulion.

p(0).
p(X) :- p(X).
p(1).
The queiy p(X) ieluins lhe infeiied facls fion lhe piogian iiiespeclive of lhe
appaienl infinile iecuision in lhe second iuIe. (Nole lhal lhe IioIog goaI p(1) does nol
leininale. You can easiIy check il oul vilh /prolog p(1).)
"." Aransiti0e Closure D:iles tranclosure.{dl,sql,ra}E
Wilh lhis exanpIe, ve shov a possilIe use of nuluaI iecuision ly neans of a
DalaIog piogian lhal defines lhe liansilive cIosuie of lhe ieIalions p and q
13
. Il can le
consuIled vilh /c tranclosure.

p(a,b).
p(c,d).
q(b,c).
q(d,e).
pqs(X,Y) :- p(X,Y).
pqs(X,Y) :- q(X,Y).
pqs(X,Y) :- pqs(X,Z),p(Z,Y).
pqs(X,Y) :- pqs(X,Z),q(Z,Y).
The queiy pqs(X,Y) ieluins lhe vhoIe sel of infeiied facls lhal nodeI lhe
liansilive cIosuie.
IiIe tranclosure.sql conlains lhe SQL counleipail code, vhich can le
execuled vilh /process tranclosure.sql:

create table p(x,y);
insert into p values ('a','b');

13
Taken fion |Diel87j.


Fernando Senz-Prez 2!4/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

insert into p values ('c','d');
create table q(x,y);
insert into q values ('b','c');
insert into q values ('d','e');
create view pqs(x,y) as
select * from p
union
select * from q
union select pqs.x,p.y from pqs,p where pqs.y=p.x
union select pqs.x,q.y from pqs,q where pqs.y=q.x;
The queiy select * from pqs ieluins lhe sane ansvei as lefoie.
IiIe tranclosure.ra conlains lhe RA foinuIalion:

pqs(x,y) :=
p
union
q
union
project pqs.x,p.y (pqs zjoin pqs.y=p.x p)
union
project pqs.x,q.y (pqs zjoin pqs.y=q.x q);

/ra select true (pqs)
".( Mutual +ecursion D:iles mutrecursion.{dl,sql,ra}E
The foIIoving piogian shovs a lasic exanpIe aloul nuluaI iecuision:
p(a).
p(b).
q(c).
q(d).
p(X) :- q(X).
q(X) :- p(X).
Sulnilling lhe goaI p(X), ve gel:
{
p(a),
p(b),
p(c),
p(d)
}
Info: 4 tuples computed.
vhich is lhe sane sel of vaIues foi aigunenls foi lhe queiy q(X). The fiIe
mrtc.dl is a conlinalion of lhis exanpIe and lhal of lhe pievious seclion.
The fiIe mutrecursion.sql conlains lhe SQL counleipail code, vhich can le
execuled vilh /process mutrecursion.sql:

/sql
/assert p(a)
/assert p(b)
/assert q(c)
/assert q(d)


Fernando Senz-Prez 2!5/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

-- View q must be given a prototype for view p to be defined
create view q(x) as select * from q;
create or replace view p(x) as select * from q;
create or replace view q(x) as select * from p;
Nole lhal il is needed lo luiId a void viev foi q in oidei lo have il decIaied
vhen defining lhe viev p. The void viev is lhen iepIaced ly ils acluaI definilion. The
conlenls of lolh vievs can le lesled lo le equaI vilh:

select * from p;
select * from q;
IiIe mutrecursion.ra conlains lhe RA foinuIalion:

-- View q must be given a prototype for view p to be defined
q(x) := select true (q);
p(x) := select true (q);
q(x) := select true (p);

select true (p);
select true (q);
".8 .armerG,ol:G!oatGCa**age ?uJJle D:ile puzzle.dlE
This exanpIe
14
shovs lhe cIassic Iainei-WoIf-Coal-Callage puzzIe (aIso
Missionaiies and CannilaIs as anolhei ieviillen foin). The fainei, voIf, goal, and
callage aie aII on lhe noilh shoie of a iivei and lhe piolIen is lo liansfei lhen lo lhe
soulh shoie. The fainei has a loal vhich he can iov laking al nosl one passengei al a
line. The goal cannol le Iefl vilh lhe voIf unIess lhe fainei is piesenl. The callage,
vhich counls as a passengei, cannol le Iefl vilh lhe goal unIess lhe fainei is piesenl.
The foIIoving piogian nodeIs lhe soIulion lo lhis puzzIe. The ieIalion state/4
defines lhe vaIid slales undei lhe specificalion (i.e., lhose silualions in vhich lheie is
no dangei foi any of lhe chaiacleis in oui sloiy, a slale in vhich lhe goal is Iefl aIone
vilh lhe callage nay iesuIl in an ealen callage) and inposes lhal lheie is a pievious
vaIid slale fion vhich ve depail fion. The aigunenls of lhis ieIalion aie inlended lo
iepiesenl (fion Iefl lo iighl) lhe posilion (noilh -n- oi soulh -s- shoie) of lhe fainei,
voIf, goal, and callage. We use lhe ieIalion safe/4 lo veiify lhal a given
configuialion of posilions is vaIid. The ieIalion opp/2 sinpIy slales lhal noilh is lhe
opposile shoie of soulh and vice veisa.

% Initial state
state(n,n,n,n).
% Farmer takes Wolf
state(X,X,U,V) :-
safe(X,X,U,V),
opp(X,X1),
state(X1,X1,U,V).
% Farmer takes Goat
state(X,Y,X,V) :-
safe(X,Y,X,V),

14
Adapled fion |Diel87j.


Fernando Senz-Prez 2!6/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

opp(X,X1),
state(X1,Y,X1,V).
% Farmer takes Cabbage
state(X,Y,U,X) :-
safe(X,Y,U,X),
opp(X,X1),
state(X1,Y,U,X1).
% Farmer goes by himself
state(X,Y,U,V) :-
safe(X,Y,U,V),
opp(X,X1),
state(X1,Y,U,V).

% Opposite shores (n/s)
opp(n,s).
opp(s,n).

% Farmer is with Goat
safe(X,Y,X,V).
% Farmer is not with Goat
safe(X,X,X1,X) :- opp(X,X1).
If ve sulnil lhe queiy state(s,s,s,s), ve gel lhe expecled iesuIl:
{
state(s,s,s,s)
}
Info: 1 tuple computed.
Thal is, lhe syslen has pioved lhal lheie is a seiiaI of liansfeis lelveen shoies
vhich finaIIy end vilh lhe asked configuialion (lhis piolIen is nol nodeIed lo shov
lhis seiiaI). If ve ask foi lhe exlension lalIe conlenls iegaiding lhe ieIalion state/4
(vilh lhe connand /list_et state/4), ve gel foi lhe ansveis:
{
state(n,n,n,n),
state(n,n,n,s),
state(n,n,s,n),
state(n,s,n,n),
state(n,s,n,s),
state(s,n,s,n),
state(s,n,s,s),
state(s,s,n,s),
state(s,s,s,n),
state(s,s,s,s)
}
Info: 10 tuples in the answer set.
This is lhe conpIele sel of vaIid slales vhich incIudes aII of lhe vaIid palhs fion
state(n,n,n,n) lo state(s,s,s,s). Hovevei, lhe oidei of slales lo ieach lhe
Iallei is nol given, lul ve can find il ly olseiving lhis ieIalion, i.e.:

state(n,n,n,n) Farmer takes Goat to south shore
state(s,n,s,n) Farmer returns to north shore
state(n,n,s,n) Farmer takes Wolf to south shore
state(s,s,s,n) Farmer takes Goat to north shore


Fernando Senz-Prez 2!7/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

state(n,s,n,n) Farmer takes Cabbage to south shore
state(s,s,n,s) Farmer returns to north shore
state(n,s,n,s) Farmer takes Goat to south shore
state(s,s,s,s) Final safe state
Olseive lhal lheie is lvo slales in lhe ieIalion state/4 vhich do nol foin pail
of lhe pievious palh:

state(s,n,s,s)
state(n,n,n,s)
These slales cone fion anolhei possilIe palh:
15


state(n,n,n,n) Farmer takes Goat to south shore
state(s,n,s,n) Farmer returns to north shore
state(n,n,s,n) Farmer takes Cabbage to south shore
state(s,n,s,s) Farmer takes Goat to north shore
state(n,n,n,s) Farmer takes Wolf to south shore
state(s,s,s,n) Farmer takes Goat to north shore
state(s,s,n,s) Farmer returns to north shore
state(n,s,n,s) Farmer takes Goat to south shore
state(s,s,s,s) Final safe state
".8.1 Dealing 3it/ &at/s D:ile puzzle1.dlE
As jusl iIIuslialed, lhe sequence of novenenls needed lo find a feasilIe
soIulion can le infeiied fion lhe ansvei lalIe. NonelheIess, il is possilIe lo oulcone
such sequences even vhen lheie is no piovision foi dala sliucluies. The idea is lo code
sequences of novenenls inlo a singIe pIain lype, as an inlegei. We can iesoil, foi
inslance, lo luiId a decinaI nunlei vhose digils, as iead fion right to left, indicale lhe
seIecled novenenl in lhe sequence. If ve nunlei lhe novenenl aIleinalives fion 1 lo
4 (in lhe sane oidei as iuIes occui al lhe piogian lexl) lhe fiisl soIulion alove can le
coded as 2412342, and lhe second one as 2432142.
ModeIing in lhis vay, ve can ieviile lhe piedicale slale ly adding a fiisl
aigunenl as lhe sequence needed lo ieach a given slale, and lhe slelps aIieady
peifoined. This is usefuI lo luiId lhe code as adding a nunlei (idenlifying lhe
aIleinalive iuIe) nuIlipIied ly lhe n-lh povei of len, vheie n is lhe nunlei of sleps
aIieady done. The foIIoving lvo exanpIe iuIes iIIusliales lhis:

% 0. Initial state
state(0,0,n,n,n,n).
% 1. Farmer takes Wolf
state(C,S,X,X,U,V) :-
safe(X,X,U,V),
opp(X,X1),
state(C1,S1,X1,X1,U,V),
S is S1+1,
bound(B),
S<B,

15
Renenlei lhal lhe syslen ieluins all of lhe possilIe soIulions.


Fernando Senz-Prez 2!8/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

C is C1+1*10**S1.
SoIving lhe nev piogian yieIds:

DES> state(C,S,s,s,s,s)
{
state(2412342.0,7,s,s,s,s),
state(2432142.0,7,s,s,s,s)
}
Info: 2 tuples computed.
Which is expIained as foIIovs:

* Solution 1: state(2412342.0,7,s,s,s,s)
0: Initial state
North: Farmer,Goat,Cabbage,Wolf
South: empty
2: Farmer takes goat to the South shore
North: Cabbage,Wolf
South: Farmer,Goat
4: Farmer returns to North shore
North: Farmer,Cabbage,Wolf
South: Goat
3: Farmer takes cabbage to the South shore
North: Wolf
South: Farmer,Cabbage,Goat
2: Farmer takes goat to the North shore
North: Farmer,Goat,Wolf
South: Cabbage
1: Farmer takes wolf to the South shore
North: Goat
South: Farmer,Cabbage,Wolf
4: Farmer returns to North shore
North: Farmer,Goat
South: Cabbage,Wolf
2: Farmer takes goat to the South shore
North: empty
South: Farmer,Goat,Cabbage,Wolf

* Solution 2: state(2432142.0,7,s,s,s,s)
0: Initial state
North: Farmer,Goat,Cabbage,Wolf
South: empty
2: Farmer takes goat to the South shore
North: Cabbage,Wolf
South: Farmer,Goat
4: Farmer returns to North shore
North: Farmer,Cabbage,Wolf
South: Goat
1: Farmer takes wolf to the South shore
North: Cabbage
South: Farmer,Goat,Wolf
2: Farmer takes goat to the North shore
North: Farmer,Goat,Cabbage
South: Wolf


Fernando Senz-Prez 2!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

3: Farmer takes cabbage to the South shore
North: Goat
South: Farmer,Cabbage,Wolf
4: Farmer returns to North shore
North: Farmer,Goat
South: Cabbage,Wolf
2: Farmer takes goat to the South shore
North: empty
South: Farmer,Goat,Cabbage,Wolf

". ?arado)es D:iles russell.{dl,sql,ra}E
When negalion is used, ve can find paiadoxes, such as lhe RusseIIs paiadox
(lhe lailei in a lovn shaves eveiy peison vho does nol shave hinseIf) shovn in lhe
nexl exanpIe (pIease nole lhal lhis exanpIe is nol slialified and, in geneiaI, ve cannol
ensuie coiieclness foi non-slialifialIe piogians):

DES> /verbose on
Info: Verbose output is on.

DES> /c russell
Info: Consulting russell...
shaves(barber,M) :-
man(M),
not(shaves(M,M)).
man(barber).
man(mayor).
shaved(M) :-
shaves(barber,M).
end_of_file.
Info: 4 rules consulted.
Info: Computing predicate dependency graph...
Info: Computing strata...
Warning: Non stratifiable program.
If ve sulnil lhe queiy shaves(X,Y), ve gel lhe posilive facls as veII as a sel
of undefined infeiied infoinalion (in oui exanpIe, vhelhei lhe lailei shaves hinseIf),
as foIIovs (heie, veilose oulpul is enalIed):

DES> shaves(X,Y)
Warning: Unable to ensure correctness for this query.
{
shaves(barber,mayor)
}
Info: 1 tuple computed.
Undefined:
{
shaves(barber,barber)
}
Info: 1 tuple undefined.
If ve Iook al lhe exlension lalIe conlenls ly sulnilling lhe connand
/list_et, ve gel as ansveis:


Fernando Senz-Prez 21!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Answers:
{
man(barber),
man(mayor),
not(shaves(mayor,mayor)),
shaves(barber,mayor)
}
Info: 4 tuples in the answer set.
We can see lhal, in pailicuIai, ve have pioved addilionaI negalive infoinalion
(lhe nayoi does nol shaves hinseIf) and lhal no infoinalion is given foi lhe undefined
facls. The cuiienl inpIenenlalion uses an inconpIele aIgoiilhn foi finding such
undefined facls. We can see lhis inconpIeleness ly adding lhe foIIoving iuIe:

shaved(M) :- shaves(barber,M).
The queiy shaved(M) ieluins:

Warning: Unable to ensure correctness for this query.
{
shaved(mayor)
}
Info: 1 tuple computed.
Thal is, lhe syslen is unalIe lo piove lhal shaved(barber) is undefined.
If you Iook al lhe piedicale dependency giaph and lhe slialificalion of lhe
piogian:

DES> /pdg

Nodes: [man/1,shaved/1,shaves/2]
Arcs : [shaves/2-shaves/2,shaves/2+man/1,shaved/1+shaves/2]

DES> /strata

[non-stratifiable]
you gel lhe piedicale dependency giaph shovn in Iiguie 4, and you aie infoined lhal
lhe piogian is non-slialifialIe. This figuie shovs a negalion in a cycIe, so lhal lhe
piogian is nol slialifialIe. (The syslen vained of lhis silualion vhen lhe piogian vas
Ioaded.)

+
shaves
man shaved
+
-

Iiguie 4. Iiedicale Dependency Ciaph foi russell.dl
Hovevei, even vhen a piogian is non-slialifialIe, lheie nay exisl a queiy vilh
an associaled piedicale dependency sulgiaph so lhal negalion does nol occui in any
cycIe. Ioi inslance, lhis occuis vilh lhe queiy man(X) in lhis piogian:


Fernando Senz-Prez 211/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


DES> man(X)
Info: Stratifiable subprogram found for the given query.
{
man(barber),
man(mayor)
}
Info: 2 tuples computed.
Heie, lhe syslen ieconpuled lhe sliala foi lhe piedicale dependency sulgiaph,
and infoined lhal il found a slialifialIe sulpiogian foi such a queiy. In lhis sinpIe
case, no noie negalions veie invoIved in lhe sulgiaph, lul noie eIaloialed
dependencies can le found in olhei exanpIes (cf. Seclions 6.1O and 6.11).
Slialificalion nay le needed foi piogians vilhoul negalion as Iong as a
lenpoiaiy viev conlains a negaled goaI. Considei lhe foIIoving viev undei lhe
piogian relop.dl (iuIes in lhe piogian vilh negalion aie nol piesenl in lhe
sulgiaph foi lhe queiy d(X)):

DES> d(X) :- a(X), not(b(X))
Info: Processing:
d(X) :- a(X),not(b(X)).
{
d(a2),
d(a3)
}
Info: 2 tuples computed.
In lhis viev, lhe queiy d(X) is soIved vilh a soIve-ly-slialun aIgoiilhn,
desciiled in Seclion 5.17.3. In lhis case, lhis neans lhal lhe goaI b(X) is soIved lefoie
ollaining lhe neaning of d(X) lecause b is in a Iovei slialun lhan d and il is needed
foi lhe conpulalion of d.
The lasic paiadox p:-not(p) can le found in lhe fiIe paiadox.dI, vhose
nodeI is undefined as you can lesl vilh lhe queiy p.
".1' ?arity D:ile parity.dlE
This exanpIe piogian
16
is inlended lo conpule lhe paiily of a given lase
ieIalion br(X), i.e., il can deleinine vhelhei lhe nunlei of eIenenls in lhe ieIalion
(caidinaIily) is even oi odd ly neans of lhe piedicales br_is_even, and br_is_odd,
iespecliveIy. The piedicale next defines an ascending chain of eIenenls in br lased
on lheii lexluaI oideiing, vheie lhe fiisl Iink of lhe chain connecls lhe dislinguished
node nil lo lhe fiisl eIenenl in br. The piedicales even and odd define lhe even,
iesp. odd, eIenenls in lhe chain. The piedicale has_preceding defines lhe eIenenls
in br such lhal lheie aie pievious eIenenls lo a given one (lhe fiisl eIenenl in lhe
chain has no pieceding eIenenls). The iuIe defining lhis piedicale incIudes an
inlended eiioi (fouilh iuIe in lhe exanpIe) vhich viII le used in Seclion 6.13 lo shov
hov il is caughl ly lhe decIaialive deluggei.

% Pairs of non-consecutive elements in br

16
Adapled fion |ZCI+97j.


Fernando Senz-Prez 212/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

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

% Consecutive elements in the sequence, starting at nil
next(X,Y) :-
br(X), br(Y), X<Y, not(between(X,Y)).
next(nil,X) :-
br(X), not(has_preceding(X)).

% Values having preceding values in the sequence
has_preceding(X) :-
br(X), br(Y), Y>X. %error: Y>X should be Y<X

% Values in an even position of the sequence, including nil
even(nil).
even(Y) :-
odd(X), next(X,Y).

% Values in an odd position of the sequence
odd(Y) :-
even(X), next(X,Y).

% Succeeds if the cardinality of the sequence is even
br_is_even :-
even(X), not(next(X,Y)).

% Succeeds if the cardinality of the sequence is odd
br_is_odd :-
odd(X), not(next(X,Y)).

% Base relation
br(a).
br(b).
".11 !rammar D:ile grammar.dlE
Iaiseis can aIso le coded as DalaIog piogians. In lhis exanpIe
17
, a sinpIe Iefl-
iecuisive giannai anaIysei is coded foi lhe foIIoving giannai iuIes.
A -> a
A -> Al
A -> Aa
Il vas lesled vilh lhe inpul sliing alala, vhich is coded vilh lhe ieIalion
t(F,T,L), F foi lhe posilion of loken T lhal ends al posilion L.

t(1,a,2).
t(2,b,3).
t(3,a,4).
t(4,b,5).
t(5,a,6).

17
Taken fion |ID92j.


Fernando Senz-Prez 213/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

a(F,L) :- t(F,a,L).
a(F,L) :- a(F,M), t(M,b,L).
a(F,L) :- a(F,M), t(M,a,L).
DES> a(1,6)
{
a(1,6)
}
Info: 1 tuple computed.
".12 .i*onacci D:ile fib.{dl,sql,ra}E
The aII-line cIassics Iilonacci piogian
18
can le coded in DLS lhanks lo
aiilhnelic luiIl-ins. Il can le foinuIaled as foIIovs:

fib(0,1).
fib(1,1).
fib(N,F) :-
N>1,
N2 is N-2,
fib(N2,F2),
N1 is N-1,
fib(N1,F1),
F is F2+F1.
Since DLS is inpIenenled vilh exlension lalIes, conpuling high Iilonacci
nunleis is possilIe vilh Iineai conpIexily:

DES> fib(1000,F)
{
fib(1000,7033036771142281582183525487718354977018126983635873274
2604905087154537118196933579742249494562611733487750449241765991
0881863632654502236471060120533741212738673391111981393731255987
67690091902245245323403501)
}
Info: 1 tuple computed.
AIso, il is possilIe lo foinuIale lhis in SQL, even vhen lhe nexl viev fealuies
non-Iineai iecuision (fiIe fib.sql):

create view fib(n,f) as
select 0,1
union
select 1,1
union
select fib1.n+1,fib1.f+fib2.f
from fib fib1, fib fib2
where fib1.n=fib2.n+1 and fib1.n<10;
As veII, nexl lheie is a possilIe RA foinuIalion (fiIe fib.ra):

fib(n,f) :=
project 0,1 (dual)

18
Taken fion |ID92j.


Fernando Senz-Prez 214/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

union
project 1,1 (dual)
union
project fib1.n+1,fib1.f+fib2.f
(rename fib1(n1,f1) (fib)
zjoin
n1=n2+1 and n1<10
rename fib2(n2,f2) (fib));
".13 @anoi Ao3ers D:ile hanoi.dlE
Anolhei veII-knovn loy puzzIe is lhe loveis of Hanoi, vhich can le coded as:

hanoi(1,A,B,C).
hanoi(N,A,B,C) :-
N>1,
N1 is N-1,
hanoi(N1,A,C,B),
hanoi(N1,C,B,A).
We can sulnil lhe foIIoving queiy foi 1O discs:

DES> hanoi(10,a,b,c)
{
hanoi(10,a,b,c)
}
Info: 1 tuple computed.
Nole lhal lhe ansvei lo lhis queiy does nol iefIecl lhe novenenls of lhe discs,
vhich can le olheivise shovn as lhe inleinediale iesuIls kepl in lhe exlension lalIe:

DES> /list_et hanoi
Answers:
{
hanoi(1,a,c,b),
hanoi(1,b,a,c),
hanoi(1,c,b,a),
hanoi(2,a,b,c),
hanoi(2,b,c,a),
hanoi(2,c,a,b),
hanoi(3,a,c,b),
hanoi(3,b,a,c),
hanoi(3,c,b,a),
hanoi(4,a,b,c),
hanoi(4,b,c,a),
hanoi(4,c,a,b),
hanoi(5,a,c,b),
hanoi(5,b,a,c),
hanoi(5,c,b,a),
hanoi(6,a,b,c),
hanoi(6,b,c,a),
hanoi(6,c,a,b),
hanoi(7,a,c,b),
hanoi(7,b,a,c),
hanoi(7,c,b,a),


Fernando Senz-Prez 215/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

hanoi(8,a,b,c),
hanoi(8,b,c,a),
hanoi(8,c,a,b),
hanoi(9,a,c,b),
hanoi(9,c,b,a),
hanoi(10,a,b,c)
}
Info: 27 tuples in the answer set.
...
".14 =t/er E)am&les
Diiecloiy exanpIes incIude sone olhei exanpIes as lhe fiIes bom.dl (liII of
naleiiaIs) and trains.dl (liain conneclions) vhich shov noie exanpIe appIicalions
incIuding negalion. Olhei exanpIes aie orbits.dl (a cosnos liny dalalase), sg.dl
(sane geneialion foi a faniIy dalalase), tc.dl (liansilive cIosuie), and
empTraining.{ra,sql} (laken fion |DielO1j). AIso, lhe foIdei persistent
conlains exanpIes foi peisisling piedicales, lhe foIdei ontology incIudes exanpIes of
aulhoiing onloIogies, incIuding sone docunenlalion, and foIdeis DLDebugger and
SQLDebugger incIude exanpIes foi delugging DalaIog piogians and SQL vievs,
iespecliveIy.
(. Contri*utions
This seclion coIIecls lhe conliilulions fion exleinaI deveIopeis up lo nov:
Tesl Case Ceneialoi.
Authors: RafaeI CalaIIeio-RoIdn, YoIanda Caica-Ruiz, and Ieinando Senz-Ieiez
.ate: 1O/2OO9 (upgiaded veision suppoiled since DLS 1.8.O)
.escription: TooI foi geneialing lesl cases foi SQL vievs
/icense: LCIL
0ontact: YoIanda Caica-Ruiz (InpIenenloi)
DalaIog DecIaialive Deluggei.
Authors: RafaeI CalaIIeio-RoIdn, YoIanda Caica-Ruiz, and Ieinando Senz-Ieiez
.ate: 5/2OO7
.escription: TooI foi lhe decIaialive delugging of DalaIog piogians
/icense: LCIL
0ontact: YoIanda Caica-Ruiz (InpIenenloi)
ACIDL (A ConfiguialIe DeveIopnenl Lnviionnenl).
Authors+ Diego CaidieI Iieiie, }uan }ose Oiliz Snchez, DeIfn Rupeiez Caas (SI
2OO6/2OO7), MigueI Mailn Lzaio (SI 2OO7/2OO8), and }aviei SaIcedo Cnez (SI
2O1O/2O11), IalIo Culieiiez Caica-Iaido, LIena Tejeiio Ieiez de gieda, Andies
Vicenle deI Cuia (SI 2O12/2O13) Ied ly Ieinando Senz.
.ate: 3/2OO7 (ACIDL O.1, fiisl veision), 11/2OO8 (ACIDL O.7), 7/2O11 (ACIDL O.8),
12/2O12 (ACIDL O.9, cuiienl veision)
.escription+ This piojecl is ained lo piovide a nuIlipIalfoin configuialIe
inlegialed deveIopnenl enviionnenl vhich can le configuied in oidei lo le used
vilh any deveIopnenl syslen such as inleipieleis, conpiIeis and dalalase
syslens. Iealuies of lhis syslen incIude: piojecl nanagenenl, nuIlifiIe ediling,
synlax coIouiing, and paising on-lhe-fIy (vhich infoins of synlax eiiois vhen


Fernando Senz-Prez 216/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

ediling piogians piioi lo lhe conpiIalion).
/icense: CIL.
Pro1ect 2eb Page: http://acide.sourceforge.net/
Lnacs deveIopnenl enviionnenl.
Author+ Maikus Tiiska.
.ate: 2/22/2OO7
.escription+ Iiovides an inlegialion of DLS inlo Lnacs. Once a DalaIog fiIe has
leen opened, you can consuIl il ly piessing I1 and sulnil queiies and connands
fion Lnacs. This voiks al Ieasl in conlinalion vilh SWI-IioIog (il depends on lhe
-s svilch), olhei syslens nay iequiie sIighl nodificalions.
/icense: CIL.
Pro1ect 2eb Page: http://stud4.tuwien.ac.at/~e0225855/index.html
0ontact: markus.triska@gmx.at
Installation: Copy des.el (in lhe conliilulois vel page) lo youi hone diiecloiy
and add lo youi .emacs:
(load "~/des")
; adapt the following path as necessary:
(setq des-prolog-file "~/des/systems/swi/des.pl")
(add-to-list 'auto-mode-alist '("\\.dl$" . des-mode))
Reslail Lnacs, open a *.dl fiIe lo Ioad il inlo a DLS piocess (lhis cuiienlIy onIy
voiks vilh SWI-IioIog). If lhe iegion is aclive, I1 consuIls lhe lexl in lhe iegion.
You can lhen inleiacl vilh DLS as on a leininaI.
8. +elated ,or-
Theie has leen a high anounl of voik aiound deduclive dalalases |RU95j (ils
inleiesl deIiveied nany voikshops and confeiences foi lhis suljecl) vhich deaIl lo
seveiaI syslens. Hovevei, lo lhe lesl of oui knovIedge, lheie is no a fiiendIy syslen
oiienled lo inlioducing deduclive dalalases vilh seveiaI queiy Ianguages lo sludenls.
NeveilheIess, on lhe one hand, ve can connenl sone iepiesenlalive deduclive
dalalase syslens. On lhe olhei hand, aIso sone lechnoIogicaI liansfeis lo face ieaI-
voiId piolIens.
8.1 Deducti0e Data*ase Systems
4QL |MS11j is a iecenl deveIopnenl of a iuIe-lased dalalase queiy Ianguage
vilh negalion aIIoved in lodies and heads of iuIes, vhich is founded on a foui-vaIued
senanlics vilh liulh vaIues: liue, faIse, inconsislenl and unknovn. Il piovides neans
foi a unifoin liealnenl of Open and LocaI CIosed WoiId, olhei
nonnonolonic/connonsense foinaIisns, incIuding vaiious vaiianls of defauIl
ieasoning, auloepislenic ieasoning and olhei foinaIisns appIicalion-specific
disanligualion of inconsislenl infoinalion, incIuding defeasilIe ieasoning.
Conceplase |}}NS98j is a nuIli-usei deduclive oljecl nanagei nainIy inlended
foi concepluaI nodeIing and cooidinalion in design enviionnenls. Il is nuIlipIalfoin,
oljecl-oiienled, il enjoys inlegiily consliainls, dalalase updales and seveiaI olhei
inleiesling fealuies.
The LDL piojecl al MCC Iead lo lhe LDL++ syslen |AOTWZO3j, a deduclive
dalalase syslen vilh fealuies such as X-Y slialificalion, sel and conpIex leins,


Fernando Senz-Prez 217/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

dalalase updales and aggiegales. Il can le cuiienlIy used lhiough Inleinel using a
}ava-enalIed cIienl.
DLV |II96j is a nuIlipIalfoin syslen foi disjunclive DalaIog vilh consliainls,
liue negalion (a Ia CeIfond & Lifschilz) and queiies. Il incIudes lhe K pIanning syslen,
a fionlend foi alduclive diagnosis and Reilei's diagnosis, suppoil foi inheiilance, and
an SQL fionl-end vhich piololypes sone noveI SQL3 fealuies. DLV
D
is an exlension
of DLV vhich piovides inleifaces vilh ieIalionaI dalalases, laking advanlage of lheii
efficienl inpIenenlalions lo speed-up conpulalions.
XS |RSSWI97j (http://xsb.sourceforge.net/) is an exlended IioIog
syslen lhal can le used foi deduclive dalalase appIicalions. Il enjoys a veII-founded
senanlics foi iuIes vilh negalive IileiaIs in iuIe lodies and inpIenenls lalIing
nechanisns. Il iuns lolh on Unix/Linux and Windovs opeialing syslens. DalaIog++
|Tang99j is a fionl-end foi lhe XS deduclive dalalase syslen.
lddlddl |WLO4j slands foi DD-ased Deduclive Dalaase. Il is an
inpIenenlalion of DalaIog lhal iepiesenls lhe ieIalions using linaiy decision diagians
(DDs). DDs aie a dala sliucluie lhal can efficienlIy iepiesenl Iaige ieIalions and
piovide efficienl sel opeialions. This aIIovs lddlddl lo efficienlIy iepiesenl and
opeiale on exlieneIy Iaige ieIalions.
IRIS (Inlegialed RuIe Infeience Syslen) |IRIS2OO8j is a }ava inpIenenlalion of
an exlensilIe ieasoning engine foi expiessive iuIe-lased Ianguages piovided as an
AII. Suppoils safe oi un-safe DalaIog vilh (IocaIIy) slialified oi veII-founded negalion
as faiIuie, funclion synloIs and lollon-up iuIe evaIualion.
CoiaI |RSSS94j is a deduclive syslen vilh a decIaialive queiy Ianguage lhal
suppoils geneiaI Hoin cIauses augnenled vilh conpIex leins, sel-giouping,
aggiegalion, negalion, and ieIalions vilh lupIes lhal conlain (univeisaIIy quanlified)
vaiialIes. Il onIy iuns undei Unix pIalfoins. Theie is aIso a veision vhich aIIovs
oljecl-oiienled fealuies, caIIed CoiaI++ |SRSS93j.
ILORID (I-LOgic Reasoning In Dalalases) |KLW95j is a deduclive oljecl-
oiienled dalalase syslen suppoiling I-Logic as dala definilion and queiy Ianguage.
Wilh lhe incieasing inleiesl in senisliucluied dala, IIoiid has leen exlended foi
handIing senisliucluied dala in lhe conlexl of Infoinalion Inlegialion fion lhe
Senanlic Wel.
The NAIL! piojecl deIiveied a piololype vilh slialified negalion, veII-founded
negalion, and noduIaiily slialified negalion. Lalei, il added lhe Ianguage CIue, vhich
is essenliaIIy singIe IogicaI iuIes, vilh SQL slalenenls viapped in an inpeialive
convenlionaI Ianguage |IDR91, DMI93j. The appioach of conlining lvo Ianguages is
siniIai lo lhe afoienenlioned CoiaI, vhich uses C++. Il does nol iun on Windovs
pIalfoins.
Anolhei deduclive dalalase foIIoving lhis conlinalion of decIaialive and
inpeialive Ianguages is Rock&RoII |IIWD94j.
ADITI 2 |VRK+91j is lhe Iasl veision of a deduclive dalalase syslen vhich uses
lhe Iogic/funclionaI piogianning Ianguage Meicuiy. Il does nol iun on Windovs
pIalfoins. Theie is no fuilhei deveIopnenl pIanned foi Adili.
See aIso lhe DalaIog enliy in Wikipedia (http://en.wikipedia.org/wiki/
Datalog).


Fernando Senz-Prez 218/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

8.2 Aec/nological Arans:ers
DalaIog has leen exlensiveIy sludied and is gaining a ienovned inleiesl lhanks
lo lheii appIicalion lo onloIogies |IHHO4j, senanlic vel |CCLO9j, sociaI nelvoiks
|RSO9j, poIicy Ianguages |ICO7j, and even foi oplinizalion |CTZO5j. Conpanies as
LogicIox, Lxeuia, SennIe, and Lixlo enlody DalaIog-lased deduclive dalalase
lechnoIogies in lhe soIulions lhey deveIop. The high-IeveI expiessivily of DalaIog and
ils exlensions has lheiefoie leen acknovIedged as a poveifuI fealuie lo deaI vilh
knovIedge-lased infoinalion.
The fiisl conneiciaI oiienled deduclive dalalase syslen vas lhe Snail Dala
Syslen (SDS) and ils decIaialive queiy Ianguage DecIaialive Reasoning (DLCLARL)
|KSSD94j, vilh suppoil foi slialified negalion and sels. CuiienlIy, XS and DLV have
leen piojecled lo spin-off conpanies and lhey deveIop deduclive soIulions lo ieaI-
voiId piolIens.
. .uture En/ancements
The foIIoving Iisl (in oidei of inpoilance) suggesls sone poinls lo addiess foi
enhancing DLS:
Disjunclive heads
Infoinalion aloul cycIes invoIving negalion in lhe Ioaded piogian
ConpIele aIgoiilhn foi finding undefined infoinalion
Consliainls (ieaIs, inlegeis, enuneialed lypes)
Iiecise eiioi iepoiling foi SQL and DalaIog synlax eiiois
If you find voilhvhiIe foi youi appIicalion eilhei sone of lhe poinls alove, oi
olheis nol Iisled, pIease infoin lhe aulhoi foi liying lo guide lhe inpIenenlalion lo lhe
nosl denanded poinls.
1'. Ca0eats and $imitations
DalaIog:
o No conpound leins as aigunenls in usei ieIalions
o Teininalion is ensuied up lo aiilhnelic and hypolheses. Theie is no
piovision foi nuneiicaI lounds
o No dalalase updales via DalaIog iuIes aie aIIoved
o RuIes in consuIled fiIes nusl end vilh a dol, in conliasl lo connand
pionpl inpuls in singIe-Iine node, vheie lhe dol is oplionaI. RuIes in a
consuIled fiIe nay span on nuIlipIe Iines and an ending dol is
nandaloiy, iiiespeclive lhe nuIli-Iine node
SQL:
o Usei idenlifieis (incIuding lalIes, vievs, coIunn nanes) aie case
sensilive


Fernando Senz-Prez 21/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

o ConpulalIe SQL slalenenls foIIov lhe giannai in Seclion 4.2.8 of lhis
nanuaI. The cuiienl giannai paises exlia cIauses vhich cannol le
conpuled yel (e.g., ANY, ...)
o alch updales and deIelions aie nol alonic
o Tiansaclions aie nol inpIenenled
o NuIIs and nuII-ieIaled opealions do nol exaclIy foIIov lhe SQL slandaid
o Viev definilions in a WITH cIause aie gIolaI, in conliasl lo lhe SQL
slandaid
o Sone DMS's as IM D2 via an ODC conneclion use uppeicase usei
idenlifieis, even vhen lhey aie decIaied in Ioveicase
o See aIso Seclion 5.1.7 iegaiding ODC conneclions
SQL deluggei:
o SQL delugging is nol suppoiled foi ODC conneclions, up lo nov
Tesl case geneialoi:
o Tesl case geneialion is nol suppoiled foi ODC conneclions, up lo nov
SQL liacei:
o SQL liacing is nol suppoiled foi ODC conneclions, up lo nov
MisceIIanea:
o LnalIing dupIicales can nolalIy hain peifoinance (cf. Iilonacci
exanpIe)
o Useis shouId nol viile piedicale idenlifieis slailing vilh lhe synloI '$'.
Olheivise, unexpecled lehavioui nighl happen
o alch piocessing cannol le nesled
IioIog syslens' specific issues:
o SWI-IioIog disliilulions do nol aIIov aiilhnelic expiessions invoIving
log/2
11. +elease 1otes
This seclion Iisls ieIease noles of lhe cuiienl DLS veision.
11.1 Version 3.4 o: DES Dreleased on Decem*erI 18t/I 2'13E
Lnhancenenls:
o Nev veision of ACIDL O.12, incIuding as upgiades:
Nev IDC paneI, dispIayed eilhei vhen a /pdg connand is issued
oi on denand in lhe Viev nenu. DispIay piopeilies of lhis paneI
have leen added lo lhe appIicalion nenu
ReIocalalIe paneIs. A paneI can le diagged lo anolhei paneI
posilion, inleichanging lolh paneIs Iocalions


Fernando Senz-Prez 22!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

o RA exlended piojeclion incIudes aIso lhe possiliIily of ienanings
o Added Iisling of offending iuIes foi sel vaiialIes unsafely
o Added node infoinalion foi sel vaiialIes unsafely
o Ciealion of incoiiecl vievs no Iongei dispIays lhe geneiic eiioi nessage
o Sone incoiiecl SQL slalenenls due lo aggiegales aie calched
o Consliainls aie checked aIong updales
o DalaIog division opeialoi can le nesled
Changes:
o Sulnilling an oidei_ly ieIaled queiy oveiiides cuiienl /order_answer
fIag. Theie is no need lo sulnil /order_answer off lo nake soiled
Iislings voik
o DupIicale eIininalion (dupIicales disalIed and dislincl opeialoi) consideis
diffeienl nuIIs as lhe sane nuII, lheiefoie lehaving noie cIoseIy lo SQL
o VaiialIe oidei in conpiIed iuIes
Iixed lugs:
o The division opeialion vas incoiiecl in RA and SQL
o Aggiegales incIuded exlia lupIes aIong nesled hypolhelicaI assunplions
o Renoved undecIaied piedicale vaining foi true/O vhen occuiiing as a
condilion
o The piedicale group_by vas funclioning incoiieclIy in sone cases,
depending on pievious lalIed iesuIls
o Undefined piedicale vaining ienoved foi false/O
o SQL NOT EXISTS cIause vas incoiieclIy liansIaled ly adding a lop-1 goaI
o Conpuling lhe order_by piedicale vas onilled foi /order_answer on.
So, a queiy as top(1,order_by(t(X),[X])) nighl deIivei an incoiiecl
ansvei
o In nuIliIine node, vhen piocessing a fiIe conlaining a lal and an SQL Iine
ienaik (--), lhen lhe nexl Iine vas consideied as a pail of lhe ienaik
o uiIl-ins veie liied lo le nade peisislenl foi peisislenl iuIes incIuding
lhen
o Reliacling an ID iuIe foi a peisislenl piedicale did nol iefiesh lhe dalalase
schena
o Assuning ID iuIes in an hypolhelicaI inpIicalion Iead lo exceplions in
sone cases
o The conlinalion of lop and dislincl nelapiedicales pioduced exlia lupIes
o TiansIalion of lhe DalaIog division opeialoi Iead lo ienove head vaiialIes
nol invoIved in lhe opeialion
o Anonynous vaiialIes in consuIled iuIes veie given nanes


Fernando Senz-Prez 221/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

12. 2c-no3ledgements
The aulhoi vishes lo lhank }. WieIenakei foi pioviding such an anazing fiee
IioIog syslen and suppoiling heIp. Mals CaiIsson and Iei MiIdnei, al SICS,
suppoiled lhe deveIopnenl pioviding heIp and nev capaliIilies in lhe ODC Iiliaiy.
AIso, lhanks lo aII lhe peopIe pioviding feedlack, since lhey aie guiding DLS lo suil
noie denanded iequiienenls. Conliilulois aie speciaIIy acknovIedged: Maikus
Tiiska, foi deveIoping lhe Lnacs IDL and aIso aulhoi of lhe SWI-IioIog cIpfd Iiliaiy,
and lhe sludenls Diego CaidieI Iieiie, }uan }ose Oiliz Snchez, DeIfn Rupeiez Caas,
MigueI Mailn Lzaio, }aviei SaIcedo Cnez, IalIo Culieiiez Caica-Iaido, LIena
Tejeiio Ieiez de gieda, Andies Vicenle deI Cuia, Ieinando Oidas Loienle, }uan }ose
Maiques Oiliz, and Senianis Culieiiez Quinlana, vho deveIoped and inpioved
ACIDL. Thanks lo YoIanda Caica and RafaeI CalaIIeio foi naking possilIe lo
decIaialive delug DalaIog and SQL dalalases. They aie aIso key aulhois in lhe
incIusion of lesl case geneialion foi SQL vievs. In pailicuIai, YoIanda look lhe
inpIenenlalion effoil suppoiled ly RafaeI. CaliieI Aianda Lpez and Sonia Lslevez
Mailn geneialed Mac OSX Snov Leopaid and Leopaid execulalIes, iesp. foi veisions
up lo DLS 2.6. Lniique Mailn Mailn fixed lhe Linux disliilulion of DLS 1.5.O. IinaIIy,
lhanks lo lhe Spanish piojecls IAST-STAMI (TIN2OO8-O6622-CO3-O1), Iionelidos-CM
(S2OO9TIC-1465) and CID-UCM (UCM-SCH-CR35/1O-A-91O5O2) vhich suppoiled
lhis voik in lhe conlexl of lhe Univeisily ConpIulense of Madiid and lhe Depailnenl
of AilificiaI InleIIigence and Soflvaie Lngineeiing.


Fernando Senz-Prez 223/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

2&&endi) 2. $icense

A.1 Software License
DLS Iicensing cones fion lhe ideas of lhe Iiee Soflvaie Ioundalion. Since veision 3.O,
il is disliiluled undei veision 3 of lhe CNU Lessei CeneiaI IulIic License (LCIL),
vhich suppIenenls veision 3 of lhe CNU CeneiaI IulIic License.
DLS is fiee soflvaie: you can iedisliilule il and/oi nodify il undei lhe leins of lhe
CNU CeneiaI IulIic License as pulIished ly lhe Iiee Soflvaie Ioundalion, eilhei
veision 3 of lhe License, oi (al youi oplion) any Ialei veision.
DLS is disliiluled in lhe hope lhal il viII le usefuI, lul WITHOUT ANY WARRANTY,
vilhoul even lhe inpIied vaiianly of MLRCHANTAILITY oi IITNLSS IOR A
IARTICULAR IURIOSL. See lhe CNU CeneiaI IulIic License foi noie delaiIs.
You shouId have ieceived a copy of lhe CNU CeneiaI IulIic License aIong vilh lhis
piogian. If nol, see hllp://vvv.gnu.oig/Iicenses/.
DLS veisions piioi lo 3.O veie disliiluled undei CNU CeneiaI IulIic License (CIL).

A.2 Documentation License
!1U .ree Documentation $icense
Veision 1.3, 3 Novenlei 2OO8
Copyiighl 2OOO, 2OO1, 2OO2, 2OO7, 2OO8 Iiee Soflvaie Ioundalion, Inc.
<hllp://fsf.oig/>
Lveiyone is peinilled lo copy and disliilule veilalin copies of lhis Iicense docunenl,
lul changing il is nol aIIoved.
'. ?+E2M4$E
The puipose of lhis License is lo nake a nanuaI, lexllook, oi olhei funclionaI and
usefuI docunenl "fiee" in lhe sense of fieedon: lo assuie eveiyone lhe effeclive
fieedon lo copy and iedisliilule il, vilh oi vilhoul nodifying il, eilhei conneiciaIIy
oi nonconneiciaIIy. SecondaiiIy, lhis License pieseives foi lhe aulhoi and pulIishei a
vay lo gel ciedil foi lheii voik, vhiIe nol leing consideied iesponsilIe foi
nodificalions nade ly olheis.
This License is a kind of "copyIefl", vhich neans lhal deiivalive voiks of lhe
docunenl nusl lhenseIves le fiee in lhe sane sense. Il conpIenenls lhe CNU CeneiaI
IulIic License, vhich is a copyIefl Iicense designed foi fiee soflvaie.
We have designed lhis License in oidei lo use il foi nanuaIs foi fiee soflvaie, lecause
fiee soflvaie needs fiee docunenlalion: a fiee piogian shouId cone vilh nanuaIs
pioviding lhe sane fieedons lhal lhe soflvaie does. ul lhis License is nol Iiniled lo
soflvaie nanuaIs, il can le used foi any lexluaI voik, iegaidIess of suljecl nallei oi
vhelhei il is pulIished as a piinled look. We ieconnend lhis License piincipaIIy foi
voiks vhose puipose is insliuclion oi iefeience.
1. 2??$IC24I$IAK 21D DE.I1IAI=1S


Fernando Senz-Prez 224/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

This License appIies lo any nanuaI oi olhei voik, in any nediun, lhal conlains a
nolice pIaced ly lhe copyiighl hoIdei saying il can le disliiluled undei lhe leins of
lhis License. Such a nolice gianls a voiId-vide, ioyaIly-fiee Iicense, unIiniled in
duialion, lo use lhal voik undei lhe condilions slaled heiein. The "Docunenl", leIov,
iefeis lo any such nanuaI oi voik. Any nenlei of lhe pulIic is a Iicensee, and is
addiessed as "you". You accepl lhe Iicense if you copy, nodify oi disliilule lhe voik
in a vay iequiiing peinission undei copyiighl Iav.
A "Modified Veision" of lhe Docunenl neans any voik conlaining lhe Docunenl oi a
poilion of il, eilhei copied veilalin, oi vilh nodificalions and/oi liansIaled inlo
anolhei Ianguage.
A "Secondaiy Seclion" is a naned appendix oi a fionl-nallei seclion of lhe Docunenl
lhal deaIs excIusiveIy vilh lhe ieIalionship of lhe pulIisheis oi aulhois of lhe
Docunenl lo lhe Docunenl's oveiaII suljecl (oi lo ieIaled nalleis) and conlains
nolhing lhal couId faII diieclIy vilhin lhal oveiaII suljecl. (Thus, if lhe Docunenl is in
pail a lexllook of nalhenalics, a Secondaiy Seclion nay nol expIain any
nalhenalics.) The ieIalionship couId le a nallei of hisloiicaI conneclion vilh lhe
suljecl oi vilh ieIaled nalleis, oi of IegaI, conneiciaI, phiIosophicaI, elhicaI oi
poIilicaI posilion iegaiding lhen.
The "Invaiianl Seclions" aie ceilain Secondaiy Seclions vhose lilIes aie designaled, as
leing lhose of Invaiianl Seclions, in lhe nolice lhal says lhal lhe Docunenl is ieIeased
undei lhis License. If a seclion does nol fil lhe alove definilion of Secondaiy lhen il is
nol aIIoved lo le designaled as Invaiianl. The Docunenl nay conlain zeio Invaiianl
Seclions. If lhe Docunenl does nol idenlify any Invaiianl Seclions lhen lheie aie none.
The "Covei Texls" aie ceilain shoil passages of lexl lhal aie Iisled, as Iionl-Covei Texls
oi ack-Covei Texls, in lhe nolice lhal says lhal lhe Docunenl is ieIeased undei lhis
License. A Iionl-Covei Texl nay le al nosl 5 voids, and a ack-Covei Texl nay le al
nosl 25 voids.
A "Tianspaienl" copy of lhe Docunenl neans a nachine-ieadalIe copy, iepiesenled in
a foinal vhose specificalion is avaiIalIe lo lhe geneiaI pulIic, lhal is suilalIe foi
ievising lhe docunenl sliaighlfoivaidIy vilh geneiic lexl edilois oi (foi inages
conposed of pixeIs) geneiic painl piogians oi (foi diavings) sone videIy avaiIalIe
diaving ediloi, and lhal is suilalIe foi inpul lo lexl foinalleis oi foi aulonalic
liansIalion lo a vaiiely of foinals suilalIe foi inpul lo lexl foinalleis. A copy nade in
an olheivise Tianspaienl fiIe foinal vhose naikup, oi alsence of naikup, has leen
aiianged lo lhvail oi discouiage sulsequenl nodificalion ly ieadeis is nol
Tianspaienl. An inage foinal is nol Tianspaienl if used foi any sulslanliaI anounl of
lexl. A copy lhal is nol "Tianspaienl" is caIIed "Opaque".
LxanpIes of suilalIe foinals foi Tianspaienl copies incIude pIain ASCII vilhoul
naikup, Texinfo inpul foinal, LaTeX inpul foinal, SCML oi XML using a pulIicIy
avaiIalIe DTD, and slandaid-confoining sinpIe HTML, IoslSciipl oi IDI designed
foi hunan nodificalion. LxanpIes of lianspaienl inage foinals incIude INC, XCI
and }IC. Opaque foinals incIude piopiielaiy foinals lhal can le iead and ediled onIy
ly piopiielaiy void piocessois, SCML oi XML foi vhich lhe DTD and/oi piocessing
looIs aie nol geneiaIIy avaiIalIe, and lhe nachine-geneialed HTML, IoslSciipl oi IDI
pioduced ly sone void piocessois foi oulpul puiposes onIy.


Fernando Senz-Prez 225/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The "TilIe Iage" neans, foi a piinled look, lhe lilIe page ilseIf, pIus such foIIoving
pages as aie needed lo hoId, IegilIy, lhe naleiiaI lhis License iequiies lo appeai in lhe
lilIe page. Ioi voiks in foinals vhich do nol have any lilIe page as such, "TilIe Iage"
neans lhe lexl neai lhe nosl pioninenl appeaiance of lhe voik's lilIe, pieceding lhe
leginning of lhe lody of lhe lexl.
The "pulIishei" neans any peison oi enlily lhal disliilules copies of lhe Docunenl lo
lhe pulIic.
A seclion "LnlilIed XYZ" neans a naned sulunil of lhe Docunenl vhose lilIe eilhei is
pieciseIy XYZ oi conlains XYZ in paienlheses foIIoving lexl lhal liansIales XYZ in
anolhei Ianguage. (Heie XYZ slands foi a specific seclion nane nenlioned leIov, such
as "AcknovIedgenenls", "Dedicalions", "Lndoisenenls", oi "Hisloiy".) To "Iieseive
lhe TilIe" of such a seclion vhen you nodify lhe Docunenl neans lhal il ienains a
seclion "LnlilIed XYZ" accoiding lo lhis definilion.
The Docunenl nay incIude Waiianly DiscIaineis nexl lo lhe nolice vhich slales lhal
lhis License appIies lo lhe Docunenl. These Waiianly DiscIaineis aie consideied lo le
incIuded ly iefeience in lhis License, lul onIy as iegaids discIaining vaiianlies: any
olhei inpIicalion lhal lhese Waiianly DiscIaineis nay have is void and has no effecl
on lhe neaning of lhis License.
2. VE+42AIM C=?KI1!
You nay copy and disliilule lhe Docunenl in any nediun, eilhei conneiciaIIy oi
nonconneiciaIIy, piovided lhal lhis License, lhe copyiighl nolices, and lhe Iicense
nolice saying lhis License appIies lo lhe Docunenl aie iepioduced in aII copies, and
lhal you add no olhei condilions vhalsoevei lo lhose of lhis License. You nay nol use
lechnicaI neasuies lo olsliucl oi conlioI lhe ieading oi fuilhei copying of lhe copies
you nake oi disliilule. Hovevei, you nay accepl conpensalion in exchange foi
copies. If you disliilule a Iaige enough nunlei of copies you nusl aIso foIIov lhe
condilions in seclion 3.
You nay aIso Iend copies, undei lhe sane condilions slaled alove, and you nay
pulIicIy dispIay copies.
3. C=?KI1! I1 #U21AIAK
If you pulIish piinled copies (oi copies in nedia lhal connonIy have piinled coveis)
of lhe Docunenl, nunleiing noie lhan 1OO, and lhe Docunenl's Iicense nolice
iequiies Covei Texls, you nusl encIose lhe copies in coveis lhal caiiy, cIeaiIy and
IegilIy, aII lhese Covei Texls: Iionl-Covei Texls on lhe fionl covei, and ack-Covei
Texls on lhe lack covei. olh coveis nusl aIso cIeaiIy and IegilIy idenlify you as lhe
pulIishei of lhese copies. The fionl covei nusl piesenl lhe fuII lilIe vilh aII voids of
lhe lilIe equaIIy pioninenl and visilIe. You nay add olhei naleiiaI on lhe coveis in
addilion. Copying vilh changes Iiniled lo lhe coveis, as Iong as lhey pieseive lhe lilIe
of lhe Docunenl and salisfy lhese condilions, can le liealed as veilalin copying in
olhei iespecls.
If lhe iequiied lexls foi eilhei covei aie loo voIuninous lo fil IegilIy, you shouId pul
lhe fiisl ones Iisled (as nany as fil ieasonalIy) on lhe acluaI covei, and conlinue lhe
iesl onlo adjacenl pages.
If you pulIish oi disliilule Opaque copies of lhe Docunenl nunleiing noie lhan 1OO,
you nusl eilhei incIude a nachine-ieadalIe Tianspaienl copy aIong vilh each Opaque


Fernando Senz-Prez 226/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

copy, oi slale in oi vilh each Opaque copy a conpulei-nelvoik Iocalion fion vhich
lhe geneiaI nelvoik-using pulIic has access lo dovnIoad using pulIic-slandaid
nelvoik piolocoIs a conpIele Tianspaienl copy of lhe Docunenl, fiee of added
naleiiaI. If you use lhe Iallei oplion, you nusl lake ieasonalIy piudenl sleps, vhen
you legin disliilulion of Opaque copies in quanlily, lo ensuie lhal lhis Tianspaienl
copy viII ienain lhus accessilIe al lhe slaled Iocalion unliI al Ieasl one yeai aflei lhe
Iasl line you disliilule an Opaque copy (diieclIy oi lhiough youi agenls oi ielaiIeis)
of lhal edilion lo lhe pulIic.
Il is iequesled, lul nol iequiied, lhal you conlacl lhe aulhois of lhe Docunenl veII
lefoie iedisliiluling any Iaige nunlei of copies, lo give lhen a chance lo piovide you
vilh an updaled veision of lhe Docunenl.
4. M=DI.IC2AI=1S
You nay copy and disliilule a Modified Veision of lhe Docunenl undei lhe
condilions of seclions 2 and 3 alove, piovided lhal you ieIease lhe Modified Veision
undei pieciseIy lhis License, vilh lhe Modified Veision fiIIing lhe ioIe of lhe
Docunenl, lhus Iicensing disliilulion and nodificalion of lhe Modified Veision lo
vhoevei possesses a copy of il. In addilion, you nusl do lhese lhings in lhe Modified
Veision:
A. Use in lhe TilIe Iage (and on lhe coveis, if any) a lilIe dislincl fion lhal of lhe
Docunenl, and fion lhose of pievious veisions (vhich shouId, if lheie veie any, le
Iisled in lhe Hisloiy seclion of lhe Docunenl). You nay use lhe sane lilIe as a pievious
veision if lhe oiiginaI pulIishei of lhal veision gives peinission.
. Lisl on lhe TilIe Iage, as aulhois, one oi noie peisons oi enlilies iesponsilIe foi
aulhoiship of lhe nodificalions in lhe Modified Veision, logelhei vilh al Ieasl five of
lhe piincipaI aulhois of lhe Docunenl (aII of ils piincipaI aulhois, if il has fevei lhan
five), unIess lhey ieIease you fion lhis iequiienenl.
C. Slale on lhe TilIe page lhe nane of lhe pulIishei of lhe Modified Veision, as lhe
pulIishei.
D. Iieseive aII lhe copyiighl nolices of lhe Docunenl.
L. Add an appiopiiale copyiighl nolice foi youi nodificalions adjacenl lo lhe olhei
copyiighl nolices.
I. IncIude, innedialeIy aflei lhe copyiighl nolices, a Iicense nolice giving lhe pulIic
peinission lo use lhe Modified Veision undei lhe leins of lhis License, in lhe foin
shovn in lhe Addendun leIov.
C. Iieseive in lhal Iicense nolice lhe fuII Iisls of Invaiianl Seclions and iequiied Covei
Texls given in lhe Docunenl's Iicense nolice.
H. IncIude an unaIleied copy of lhis License.
I. Iieseive lhe seclion LnlilIed "Hisloiy", Iieseive ils TilIe, and add lo il an ilen slaling
al Ieasl lhe lilIe, yeai, nev aulhois, and pulIishei of lhe Modified Veision as given on
lhe TilIe Iage. If lheie is no seclion LnlilIed "Hisloiy" in lhe Docunenl, cieale one
slaling lhe lilIe, yeai, aulhois, and pulIishei of lhe Docunenl as given on ils TilIe
Iage, lhen add an ilen desciiling lhe Modified Veision as slaled in lhe pievious
senlence.


Fernando Senz-Prez 227/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

}. Iieseive lhe nelvoik Iocalion, if any, given in lhe Docunenl foi pulIic access lo a
Tianspaienl copy of lhe Docunenl, and Iikevise lhe nelvoik Iocalions given in lhe
Docunenl foi pievious veisions il vas lased on. These nay le pIaced in lhe "Hisloiy"
seclion. You nay onil a nelvoik Iocalion foi a voik lhal vas pulIished al Ieasl foui
yeais lefoie lhe Docunenl ilseIf, oi if lhe oiiginaI pulIishei of lhe veision il iefeis lo
gives peinission.
K. Ioi any seclion LnlilIed "AcknovIedgenenls" oi "Dedicalions", Iieseive lhe TilIe of
lhe seclion, and pieseive in lhe seclion aII lhe sulslance and lone of each of lhe
conliiluloi acknovIedgenenls and/oi dedicalions given lheiein.
L. Iieseive aII lhe Invaiianl Seclions of lhe Docunenl, unaIleied in lheii lexl and in
lheii lilIes. Seclion nunleis oi lhe equivaIenl aie nol consideied pail of lhe seclion
lilIes.
M. DeIele any seclion LnlilIed "Lndoisenenls". Such a seclion nay nol le incIuded in
lhe Modified Veision.
N. Do nol ielilIe any exisling seclion lo le LnlilIed "Lndoisenenls" oi lo confIicl in lilIe
vilh any Invaiianl Seclion.
O. Iieseive any Waiianly DiscIaineis.
If lhe Modified Veision incIudes nev fionl-nallei seclions oi appendices lhal quaIify
as Secondaiy Seclions and conlain no naleiiaI copied fion lhe Docunenl, you nay al
youi oplion designale sone oi aII of lhese seclions as invaiianl. To do lhis, add lheii
lilIes lo lhe Iisl of Invaiianl Seclions in lhe Modified Veision's Iicense nolice. These
lilIes nusl le dislincl fion any olhei seclion lilIes.
You nay add a seclion LnlilIed "Lndoisenenls", piovided il conlains nolhing lul
endoisenenls of youi Modified Veision ly vaiious pailies~foi exanpIe, slalenenls of
peei ieviev oi lhal lhe lexl has leen appioved ly an oiganizalion as lhe aulhoiilalive
definilion of a slandaid.
You nay add a passage of up lo five voids as a Iionl-Covei Texl, and a passage of up
lo 25 voids as a ack-Covei Texl, lo lhe end of lhe Iisl of Covei Texls in lhe Modified
Veision. OnIy one passage of Iionl-Covei Texl and one of ack-Covei Texl nay le
added ly (oi lhiough aiiangenenls nade ly) any one enlily. If lhe Docunenl aIieady
incIudes a covei lexl foi lhe sane covei, pieviousIy added ly you oi ly aiiangenenl
nade ly lhe sane enlily you aie acling on lehaIf of, you nay nol add anolhei, lul you
nay iepIace lhe oId one, on expIicil peinission fion lhe pievious pulIishei lhal added
lhe oId one.
The aulhoi(s) and pulIishei(s) of lhe Docunenl do nol ly lhis License give peinission
lo use lheii nanes foi pulIicily foi oi lo asseil oi inpIy endoisenenl of any Modified
Veision.
%. C=M4I1I1! D=CUME1AS
You nay conline lhe Docunenl vilh olhei docunenls ieIeased undei lhis License,
undei lhe leins defined in seclion 4 alove foi nodified veisions, piovided lhal you
incIude in lhe conlinalion aII of lhe Invaiianl Seclions of aII of lhe oiiginaI docunenls,
unnodified, and Iisl lhen aII as Invaiianl Seclions of youi conlined voik in ils Iicense
nolice, and lhal you pieseive aII lheii Waiianly DiscIaineis.


Fernando Senz-Prez 228/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

The conlined voik need onIy conlain one copy of lhis License, and nuIlipIe idenlicaI
Invaiianl Seclions nay le iepIaced vilh a singIe copy. If lheie aie nuIlipIe Invaiianl
Seclions vilh lhe sane nane lul diffeienl conlenls, nake lhe lilIe of each such seclion
unique ly adding al lhe end of il, in paienlheses, lhe nane of lhe oiiginaI aulhoi oi
pulIishei of lhal seclion if knovn, oi eIse a unique nunlei. Make lhe sane adjuslnenl
lo lhe seclion lilIes in lhe Iisl of Invaiianl Seclions in lhe Iicense nolice of lhe conlined
voik.
In lhe conlinalion, you nusl conline any seclions LnlilIed "Hisloiy" in lhe vaiious
oiiginaI docunenls, foining one seclion LnlilIed "Hisloiy", Iikevise conline any
seclions LnlilIed "AcknovIedgenenls", and any seclions LnlilIed "Dedicalions". You
nusl deIele aII seclions LnlilIed "Lndoisenenls".
". C=$$ECAI=1S =. D=CUME1AS
You nay nake a coIIeclion consisling of lhe Docunenl and olhei docunenls ieIeased
undei lhis License, and iepIace lhe individuaI copies of lhis License in lhe vaiious
docunenls vilh a singIe copy lhal is incIuded in lhe coIIeclion, piovided lhal you
foIIov lhe iuIes of lhis License foi veilalin copying of each of lhe docunenls in aII
olhei iespecls.
You nay exliacl a singIe docunenl fion such a coIIeclion, and disliilule il
individuaIIy undei lhis License, piovided you inseil a copy of lhis License inlo lhe
exliacled docunenl, and foIIov lhis License in aII olhei iespecls iegaiding veilalin
copying of lhal docunenl.
(. 2!!+E!2AI=1 ,IA@ I1DE?E1DE1A ,=+FS
A conpiIalion of lhe Docunenl oi ils deiivalives vilh olhei sepaiale and independenl
docunenls oi voiks, in oi on a voIune of a sloiage oi disliilulion nediun, is caIIed
an "aggiegale" if lhe copyiighl iesuIling fion lhe conpiIalion is nol used lo Iinil lhe
IegaI iighls of lhe conpiIalion's useis leyond vhal lhe individuaI voiks peinil. When
lhe Docunenl is incIuded in an aggiegale, lhis License does nol appIy lo lhe olhei
voiks in lhe aggiegale vhich aie nol lhenseIves deiivalive voiks of lhe Docunenl.
If lhe Covei Texl iequiienenl of seclion 3 is appIicalIe lo lhese copies of lhe
Docunenl, lhen if lhe Docunenl is Iess lhan one haIf of lhe enliie aggiegale, lhe
Docunenl's Covei Texls nay le pIaced on coveis lhal liackel lhe Docunenl vilhin
lhe aggiegale, oi lhe eIeclionic equivaIenl of coveis if lhe Docunenl is in eIeclionic
foin. Olheivise lhey nusl appeai on piinled coveis lhal liackel lhe vhoIe aggiegale.
8. A+21S$2AI=1
TiansIalion is consideied a kind of nodificalion, so you nay disliilule liansIalions of
lhe Docunenl undei lhe leins of seclion 4. RepIacing Invaiianl Seclions vilh
liansIalions iequiies speciaI peinission fion lheii copyiighl hoIdeis, lul you nay
incIude liansIalions of sone oi aII Invaiianl Seclions in addilion lo lhe oiiginaI
veisions of lhese Invaiianl Seclions. You nay incIude a liansIalion of lhis License, and
aII lhe Iicense nolices in lhe Docunenl, and any Waiianly DiscIaineis, piovided lhal
you aIso incIude lhe oiiginaI LngIish veision of lhis License and lhe oiiginaI veisions of
lhose nolices and discIaineis. In case of a disagieenenl lelveen lhe liansIalion and
lhe oiiginaI veision of lhis License oi a nolice oi discIainei, lhe oiiginaI veision viII
pievaiI.


Fernando Senz-Prez 22/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

If a seclion in lhe Docunenl is LnlilIed "AcknovIedgenenls", "Dedicalions", oi
"Hisloiy", lhe iequiienenl (seclion 4) lo Iieseive ils TilIe (seclion 1) viII lypicaIIy
iequiie changing lhe acluaI lilIe.
. AE+MI12AI=1
You nay nol copy, nodify, sulIicense, oi disliilule lhe Docunenl excepl as expiessIy
piovided undei lhis License. Any allenpl olheivise lo copy, nodify, sulIicense, oi
disliilule il is void, and viII aulonalicaIIy leininale youi iighls undei lhis License.
Hovevei, if you cease aII vioIalion of lhis License, lhen youi Iicense fion a pailicuIai
copyiighl hoIdei is ieinslaled (a) piovisionaIIy, unIess and unliI lhe copyiighl hoIdei
expIicilIy and finaIIy leininales youi Iicense, and (l) peinanenlIy, if lhe copyiighl
hoIdei faiIs lo nolify you of lhe vioIalion ly sone ieasonalIe neans piioi lo 6O days
aflei lhe cessalion.
Moieovei, youi Iicense fion a pailicuIai copyiighl hoIdei is ieinslaled peinanenlIy if
lhe copyiighl hoIdei nolifies you of lhe vioIalion ly sone ieasonalIe neans, lhis is lhe
fiisl line you have ieceived nolice of vioIalion of lhis License (foi any voik) fion lhal
copyiighl hoIdei, and you cuie lhe vioIalion piioi lo 3O days aflei youi ieceipl of lhe
nolice.
Teininalion of youi iighls undei lhis seclion does nol leininale lhe Iicenses of pailies
vho have ieceived copies oi iighls fion you undei lhis License. If youi iighls have
leen leininaled and nol peinanenlIy ieinslaled, ieceipl of a copy of sone oi aII of lhe
sane naleiiaI does nol give you any iighls lo use il.
1'. .UAU+E +EVISI=1S =. A@IS $ICE1SE
The Iiee Soflvaie Ioundalion nay pulIish nev, ievised veisions of lhe CNU Iiee
Docunenlalion License fion line lo line. Such nev veisions viII le siniIai in spiiil lo
lhe piesenl veision, lul nay diffei in delaiI lo addiess nev piolIens oi conceins. See
hllp://vvv.gnu.oig/copyIefl/.
Lach veision of lhe License is given a dislinguishing veision nunlei. If lhe Docunenl
specifies lhal a pailicuIai nunleied veision of lhis License "oi any Ialei veision"
appIies lo il, you have lhe oplion of foIIoving lhe leins and condilions eilhei of lhal
specified veision oi of any Ialei veision lhal has leen pulIished (nol as a diafl) ly lhe
Iiee Soflvaie Ioundalion. If lhe Docunenl does nol specify a veision nunlei of lhis
License, you nay choose any veision evei pulIished (nol as a diafl) ly lhe Iiee
Soflvaie Ioundalion. If lhe Docunenl specifies lhal a pioxy can decide vhich fuluie
veisions of lhis License can le used, lhal pioxy's pulIic slalenenl of acceplance of a
veision peinanenlIy aulhoiizes you lo choose lhal veision foi lhe Docunenl.
11. +E$ICE1SI1!
"Massive MuIliaulhoi CoIIaloialion Sile" (oi "MMC Sile") neans any WoiId Wide Wel
seivei lhal pulIishes copyiighlalIe voiks and aIso piovides pioninenl faciIilies foi
anylody lo edil lhose voiks. A pulIic viki lhal anylody can edil is an exanpIe of
such a seivei. A "Massive MuIliaulhoi CoIIaloialion" (oi "MMC") conlained in lhe sile
neans any sel of copyiighlalIe voiks lhus pulIished on lhe MMC sile.
"CC-Y-SA" neans lhe Ciealive Connons Alliilulion-Shaie AIike 3.O Iicense
pulIished ly Ciealive Connons Coipoialion, a nol-foi-piofil coipoialion vilh a
piincipaI pIace of lusiness in San Iiancisco, CaIifoinia, as veII as fuluie copyIefl
veisions of lhal Iicense pulIished ly lhal sane oiganizalion.


Fernando Senz-Prez 23!/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

"Incoipoiale" neans lo pulIish oi iepulIish a Docunenl, in vhoIe oi in pail, as pail of
anolhei Docunenl.
An MMC is "eIigilIe foi ieIicensing" if il is Iicensed undei lhis License, and if aII voiks
lhal veie fiisl pulIished undei lhis License sonevheie olhei lhan lhis MMC, and
sulsequenlIy incoipoialed in vhoIe oi in pail inlo lhe MMC, (1) had no covei lexls oi
invaiianl seclions, and (2) veie lhus incoipoialed piioi lo Novenlei 1, 2OO8.
The opeialoi of an MMC Sile nay iepulIish an MMC conlained in lhe sile undei CC-
Y-SA on lhe sane sile al any line lefoie Augusl 1, 2OO9, piovided lhe MMC is
eIigilIe foi ieIicensing.
2DDE1DUMH @o3 to use t/is $icense :or your documents
To use lhis License in a docunenl you have viillen, incIude a copy of lhe License in
lhe docunenl and pul lhe foIIoving copyiighl and Iicense nolices jusl aflei lhe lilIe
page:

Copyright (C) YEAR YOUR NAME.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
Texts.
A copy of the license is included in the section entitled "GNU
Free Documentation License".
If you have Invaiianl Seclions, Iionl-Covei Texls and ack-Covei Texls, iepIace lhe
"vilh . Texls." Iine vilh lhis:

with the Invariant Sections being LIST THEIR TITLES, with the
Front-Cover Texts being LIST, and with the Back-Cover Texts being
LIST.
If you have Invaiianl Seclions vilhoul Covei Texls, oi sone olhei conlinalion of lhe
lhiee, neige lhose lvo aIleinalives lo suil lhe silualion.
If youi docunenl conlains nonliiviaI exanpIes of piogian code, ve ieconnend
ieIeasing lhese exanpIes in paiaIIeI undei youi choice of fiee soflvaie Iicense, such as
lhe CNU CeneiaI IulIic License, lo peinil lheii use in fiee soflvaie.


Fernando Senz-Prez 231/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen


4i*liogra&/y
|Agia88j R. AgiavaI, "AIpha: An Lxlension of ReIalionaI AIgelia lo Lxpiess a
CIass of Recuisive Queiies", ILLL Tiansaclions on Soflvaie
Lngineeiing aichive, VoIune 14 Issue 7, }uIy 1988.
|AOO8j I. Annann and }. Offull, Inlioduclion lo Soflvaie Tesling,
Canliidge Univeisily Iiess, 2OO8.
|AOTWZO3j I. Aini, K. Ong, S. Tsui, H. Wang, and C. ZanioIo, The deduclive
dalalase syslen LDL++, TILI, 3(1):61-94, 2OO3.
|ICO7j M. eckei, C. Iouinel, and A. Coidon. Design and Senanlics of a
DecenliaIized Aulhoiizalion Language. In CSI O7: Iioceedings of lhe
2Olh ILLL Conpulei Secuiily Ioundalions Synposiun, pages 3-15,
Washinglon, DC, USA, 2OO7. ILLL Conpulei Sociely.
|IIWD94j M.L. aija, N.W. Ialon, A. Ieinandes, M.H. WiIIians, A. Dinn, An
Lffeclive Deduclive Oljecl-Oiienled Dalalase Thiough Language
Inlegialion, In Iioc. of lhe 2O
lh
VLD Confeience, 1994.
|CalaO5j CalaIIeio, R., A decIaialive deluggei of incoiiecl ansveis foi
consliainl funclionaI-Iogic piogians, in: WCILI O5: Iioceedings of
lhe 2OO5 ACM SICILAN voikshop on Cuiiy and funclionaI Iogic
piogianning (2OO5), pp. 8-13.
|CCLO9j A. CaI, C. CollIol, and T. Lukasievicz. DalaIog+-: a unified appioach
lo onloIogies and inlegiily consliainls. In ICDT O9: Iioceedings of lhe
12lh InleinalionaI Confeience on Dalalase Theoiy, pages 14-3O, Nev
Yoik, NY, USA, 2OO9. ACM.
|CCSO6lj R. CalaIIeio, Y. Caica-Ruiz, and I. Senz-Ieiez, Tovaids a Sel
Oiienled CaIcuIus foi Logic Iiogianning, Iiogianacin y
Lenguajes, I. Lucio y I. Oiejas (edilois), CIMNL, pp. 41-5O, aiceIona,
Spain, Seplenlei, 2OO6.
|CCSO7j R. CalaIIeio, Y. Caica-Ruiz, and I. Senz-Ieiez, A Nev IioposaI foi
Delugging DalaIog Iiogians, 16lh InleinalionaI Woikshop on
IunclionaI and (Consliainl) Logic Iiogianning, 2OO7.
|CCSO8j R. CalaIIeio, Y. Caica-Ruiz and I. Senz-Ieiez, " #$eoretica%
Frame&or' (or t$e Dec%arati)e De*u++in+ o( Data%o+ Pro+rams In
InleinalionaI Woikshop on Senanlics in Dala and KnovIedge ases
(SDK 2OO8), L,-S 425. //0 143-15, S/rin+er. 2!!80
|CCS1Oaj R. CalaIIeio, Y. Caica-Ruiz and I. Senz-Ieiez, "//%1in+ -onstraint
Lo+ic Pro+rammin+ to S2L #est -ase 3eneration, 4n 1!t$
4nternationa% S1m/osium on Functiona% and Lo+ic Pro+rammin+
5FL6PS 2!1!7. 2O1O0
|CCS11lj R. CalaIIeio, Y. Caica-Ruiz and I. Senz-Ieiez, AIgoiilhnic
Delugging of SQL Vievs, Liglh Lishov Infoinalics Confeience,
ISI11, Novosiliisk, Akadengoiodok, Russia, }une, 2O11.


Fernando Senz-Prez 232/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

|CCS12aj R. CalaIIeio, Y. Caica-Ruiz, and I. Senz-Ieiez, "DecIaialive
Delugging of Wiong and Missing Ansveis foi SQL Vievs", In 11lh
InleinalionaI Synposiun on IunclionaI and Logic Iiogianning
(ILOIS 2O12), Spiingei, Lecluie Noles in Conpulei Science, Kole,
}apan, May, 2O12.
|Chan78j C.L. Chang, Deduce 2: Iuilhei Invesligalions of Deduclion in
ReIalionaI Dalalases, H. CaIIaiie and }. Minkei (eds.), Logic and
Dalalases, IIenun Iiess, 1978.
|Diel87j S.W. Dieliich, Lxlension TalIes: Meno ReIalions in Logic
Iiogianning, IV ILLL Synposiun on Logic Iiogianning, 1987.
|DielO1j S.W. Dieliich, Undeislanding ReIalionaI Dalalase Queiy
Languages,, Iienlice HaII, 2OO1.
|DMI93j M. Deii, S. Moiishila, and C. Ihipps, Design and InpIenenlalion of
lhe CIue-NAIL Dalalase Syslen, In Iioc. of lhe ACM SICMOD
InleinalionaI Confeience on Managenenl of Dala, pp. 147-167, 1993.
|Diax92j DiaxIei, Chi., A IoveifuI IioIog lo SQL ConpiIei, CIS-eiichl-92-61,
Cenliun fi Infoinalions und Spiachveiaileilung, Ludvig-
MaxiniIians-Univeisill Mnchen, 1992.
|ID92j C. Ian and S. W. Dieliich, "Lxlension TalIe uiIl-ins foi IioIog",
Soflvaie - Iiaclice and Lxpeiience VoI. 22 (7), pp. 573-597, }uIy 1992.
|IHHO4j R. Iikes, I.}. Hayes, and I. Hoiiocks. OWL-QL - a Ianguage foi
deduclive queiy ansveiing on lhe Senanlic Wel. }. Wel Sen., 2(1):19-
29, 2OO4.
|II96j WoIfgang Ialei and CeiaId Ifeifei. DLV honepage, since 1996. uiI
http://www.dlvsystem.com/.
|CR68j C.C. Cieen and . RaphaeI, The Use of Theoien-Iioving Techniques
in Queslion-Ansveiing Syslens, Iioceedings of lhe 23
id
ACM
NalionaI Confeience, Washinglon D.C., 1968.
|CTZO5j S. Cieco, I. Tiulilsyna, and L. Zunpano. NI DalaIog: A Logic
Language foi NI Seaich and Oplinizalion Queiies. Dalalase
Lngineeiing and AppIicalions Synposiun, InleinalionaI, O:344-353,
2OO5.
|CUWO2j H. Caicia-MoIina, }. D. UIInan, }. Widon, Dalalase Syslens: The
ConpIele ook, Iienlice-HaII, 2OO2.
|HA92j M. A. W. Houlsna and I. M. C. Apeis, " AIgeliaic oplinizalion of
iecuisive queiies", Dala & KnovIedge Lngineeiing, VoIune 7 Issue 4,
Maich 1992.
|IRIS2OO8j IRIS-Reasonei, http://iris-reasoner.org.
|ISOOOj ISO/ILC. ISO/ILC 132111-2: IioIog Slandaid. 2OOO.
|}C}+95j M. }aike, R. CaIIeisdifei, M.A. }eusfeId, M. Slaudl, S. Lheiei:
Conceplase - a deduclive oljecl lase foi nela dala nanagenenl. In
}ouinaI of InleIIigenl Infoinalion Syslens, SpeciaI Issue on Advances
in Deduclive Oljecl-Oiienled Dalalases, VoI. 4, No. 2, 167-192, 1995.


Fernando Senz-Prez 233/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

Syslen avaiIalIe al: http://www-i5.informatik.rwth-
aachen.de/CBdoc/
|KLW95j M. Kifei, C. Lausen, }. Wu, "LogicaI Ioundalions of Oljecl Oiienled
and Iiane ased Languages", }ouinaI of lhe ACM, voI. 42, p. 741-843,
1995.
|KSSD94j W. KiessIing, H. Schnidl, W. Sliauss, and C. Dnzingei, DLCLARL
and SDS: LaiIy Lffoils lo ConneiciaIize Deduclive Dalalase
TechnoIogy, VLD }ouinaI, 3, pp. 211-243, 1994.
|KT81j C. KeIIogg and L. Tiavis, Reasoning vilh Dala in a DeducliveIy
Augnenled Dala Managenenl Syslen, H. CaIIaiie, }. Minkei, and }.
NicoIas (eds.), Advances in Dala ase Theoiy, VoIune 1, IIenun
Iiess, 1981.
|LIoy87j }. LIoyd, Ioundalions of Logic Iiogianning, Spiingei VeiIag, 1987.
|Mink87j }. Minkei, Ieispeclives in Deduclive Dalalases, TechnicaI Repoil
CS-TR-1799, Univeisily of MaiyIand al CoIIege Iaik, Maich 1987.
|MN82j }. Minkei and }.-M. NicoIas, On Recuisive Axions in Deduclive
Dalalases, Infoinalion Syslens, 16(4):67O-7O2, 1991.
|MS11j }. MaIuszynski and A. SzaIas: Living vilh Inconsislency and Taning
Nonnonolonicily. To appeai in DalaIog 2.O, C. CollIol, C. Ciasso, O.
de Mooi, and A. SeIIeis, eds., LNCS 67O2, 334-398, Spiingei-VeiIag,
2O11.
|IDR91j C. Ihipps, M. A. Deii, and K.A. Ross, CIue-NAIL!: A Deduclive
Dalalase Syslen. In Iioc. of lhe ACM SICMOD Confeience on
Managenenl of Dala, pp. 3O8-317, 1991.
|Roli65j }.A. Rolinson, A Machine-Oiienled Logic ased on lhe ResoIulion
IiincipIe, }ouinaI of lhe ACM, 12:23-41, 1965.
|RSO9j R. Ronen and O. ShnueIi. LvaIualing veiy Iaige DalaIog queiies on
sociaI nelvoiks. In LDT O9: Iioceedings of lhe 12lh InleinalionaI
Confeience on Lxlending Dalalase TechnoIogy, pages 577-587, Nev
Yoik, NY, USA, 2OO9. ACM.
|RSSS94j R. Ranakiishnan, D. Siivaslava, S. Sudaishan, and I. Seshadii. The
CoiaI deduclive syslen. VLD }ouinaI, 3(2):161-21O, 1994.
|RSSWI97j I. Rao, Konslanlinos I. Sagonas, Teiiance Svifl, David Scoll Waiien,
and }uIiana Iieiie, XS: A Syslen foi LfficienlIy Conpuling WIS",
Logic Iiogianning and Non-nonolonic Reasoning, 1997.
|RU95j R. Ranakiishnan and }.D UIInan, A Suivey of Reseaich on Deduclive
Dalalase Syslens, }ouinaI of Logic Iiogianning, 23(2): 125-149,
1995.
|SD91j C. Shih and S. W. Dieliich, "Lxlension TalIe LvaIualion of DalaIog
Iiogians vilh Negalion", Iioceedings of lhe ILLL InleinalionaI
Ihoenix Confeience on Conpuleis and Connunicalions, ScollsdaIe,
AZ, Maich 1991, pp. 792-798.


Fernando Senz-Prez 234/234
Univeisidad ConpIulense de Madiid

DalaIog LducalionaI Syslen

|SaeO7j I. Senz-Ieiez, ACIDL: An Inlegialed DeveIopnenl Lnviionnenl
ConfiguialIe foi LaTeX, The IiacTeX }ouinaI, 2OO7, Nunlei 3, ISSN
1556-6994, Augusl, 2OO7.
|Shap83j Shapiio, L., AIgoiilhnic Iiogian Deugging, ACM Dislinguished
Disseilalion, MIT Iiess, 1983.
|SICSlusj SICS, http://www.sics.se/sicstus.
|SiIvO7j SiIva, }., A Conpaialive Sludy of AIgoiilhnic Delugging Slialegies,
in: Iioc. of InleinalionaI Synposiun on Logic-lased Iiogian
Synlhesis and Tiansfoinalion LOISTR 2OO6, 2OO7, pp. 134-14O.
|SRSS93j D. Siivaslava, R. Ranakiishnan, S. Sudaishan, and I. Seshadii,
CoiaI++: Adding Oljecl-Oiienlalion lo a Logic Dalalase Language,
Iioceedings of lhe InleinalionaI Confeience on Veiy Laige Dalalases,
1993.
|Tang99j Z. Tang, "DalaIog++: An Oljecl-Oiienled Iionl-Lnd Ioi The Xsl
Deduclive Dalalase Managenenl Syslen", hllp://cileseei.isl.psu.
edu/lang99dalaIog.hlnI.
|TS86j H. Tanaki and T. Salo, OLD ResoIulion vilh TaluIalion,
Iioceedings of ICLI86, Lecluie Noles on Conpulei Science 225,
Spiingei-VeiIag, 1986.
|UIIn95j }.D. UIInan. Dalalase and KnovIedge-ase Syslens, VoIs. I (CIassicaI
Dalalase Syslens) and II (The Nev TechnoIogies), Conpulei Science
Iiess, 1995.
|VRK+91j }. Vaghani, K. Rananohanaiao, D.. Kenp, Z. Sonogyi, and I.}.
Sluckey, Design Oveiviev of lhe Adili Deduclive Dalalase Syslen,
In Iioc. of lhe 7lh InlI. Conf. on Dala Lngineeiing, pp. 24O-247, 1991.
|WieIej }. WieIenakei, http://www.SWI-Prolog.org.
|WLO4j }. WhaIey and M. Lan, CIoning-lased conlexl-sensilive poinlei aIias
anaIyses using linaiy decision diagians. In: Iiog. Lang. Design and
InpI., 2OO4.
|ZCI+97j C. ZanioIo, S. Ceii, C. IaIoulsos, T.T. Snodgiass, V.S. Suliahnanian,
and R. Zicaii, "Advanced Dalalase Syslens", Moigan Kauffnann
IulIisheis, 1997.
|ZI97j U. Zukovski and . Iieilag, The Deduclive Dalalase Syslen LOLA,
In: }. Dix and U. Iuilach and A. Neiode (Lds.). Logic Iiogianning
and Nonnonolonic Reasoning. LNAI 1265, pp. 375-386. Spiingei,
1997.

S-ar putea să vă placă și