XML Views & Reasoning about Views Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems November 3, 2005 Some slide content.

Slides:



Advertisements
Similar presentations
XML: Extensible Markup Language
Advertisements

From the Calculus to the Structured Query Language Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems September 22, 2005.
Lecture 11: Datalog Tuesday, February 6, Outline Datalog syntax Examples Semantics: –Minimal model –Least fixpoint –They are equivalent Naive evaluation.
D ATABASE S YSTEMS I R ELATIONAL A LGEBRA. 22 R ELATIONAL Q UERY L ANGUAGES Query languages (QL): Allow manipulation and retrieval of data from a database.
1 XSLT – eXtensible Stylesheet Language Transformations Modified Slides from Dr. Sagiv.
Query Execution, Concluded Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems November 18, 2003 Some slide content may.
F22H1 Logic and Proof Week 7 Clausal Form and Resolution.
Virtual Data Integration Helena Galhardas DEI IST (based on the slides of the course: CIS 550 – Database & Information Systems, Univ. Pennsylvania, Zachary.
Advanced Views: XML-Relational Storage and Datalog Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems November 8, 2005.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Relational Algebra Chapter 4, Part A Modified by Donghui Zhang.
1 Relational Algebra & Calculus. 2 Relational Query Languages  Query languages: Allow manipulation and retrieval of data from a database.  Relational.
Query Evaluation. An SQL query and its RA equiv. Employees (sin INT, ename VARCHAR(20), rating INT, age REAL) Maintenances (sin INT, planeId INT, day.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 52 Database Systems I Relational Algebra.
By relieving the brain of all unnecessary work, a good notation sets it free to concentrate on more advanced problems, and, in effect, increases the mental.
Conjunctive Queries, Datalog, and Recursion Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems October 23, 2003 Some slide.
Querying XML: XQuery and XSLT Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems October 21, 2004 Some slide content courtesy.
XML Views & Reasoning about Views Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems November 4, 2004 Some slide content.
CSE 636 Data Integration Datalog Rules / Programs / Negation Slides by Jeffrey D. Ullman.
Introduction to SQL, the Structured Query Language Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems September 16, 2003.
1 COS 425: Database and Information Management Systems XML and information exchange.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Relational Algebra Chapter 4, Part A.
Relational Algebra & Calculus Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems September 21, 2004 Some slide content.
Recursive Views and Global Views Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems November 9, 2004 Some slide content.
XML Querying and Views Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems November 1, 2005 Some slide content courtesy.
Views: Alternate Data Representations Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems November 2, 2004 Some slide content.
XML –Query Languages, Extracting from Relational Databases ADVANCED DATABASES Khawaja Mohiuddin Assistant Professor Department of Computer Sciences Bahria.
By relieving the brain of all unnecessary work, a good notation sets it free to concentrate on more advanced problems, and, in effect, increases the mental.
1 Relational Algebra and Calculus Yanlei Diao UMass Amherst Feb 1, 2007 Slides Courtesy of R. Ramakrishnan and J. Gehrke.
Rutgers University Relational Algebra 198:541 Rutgers University.
XML Querying and Views Helena Galhardas DEI IST (slides baseados na disciplina CIS 550 – Database & Information Systems, Univ. Pennsylvania, Zachary Ives)CIS.
Relational Algebra Wrap-up and Relational Calculus Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems September 11, 2003.
XML-to-Relational Schema Mapping Algorithm ODTDMap Speaker: Artem Chebotko* Wayne State University Joint work with Mustafa Atay,
1 Relational Algebra and Calculus Chapter 4. 2 Relational Query Languages  Query languages: Allow manipulation and retrieval of data from a database.
CS1Q Computer Systems Lecture 8
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 6 XSLT (Based on Møller and Schwartzbach,
The Relational Model: Relational Calculus
Chapter 2 Adapted from Silberschatz, et al. CHECK SLIDE 16.
XML A web enabled data description language 4/22/2001 By Mark Lawson & Edward Ryan L’Herault.
Copyrighted material John Tullis 10/17/2015 page 1 04/15/00 XML Part 3 John Tullis DePaul Instructor
Relational Algebra & Calculus Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems September 12, 2007 Some slide content.
Querying XML – Concluded Introduction to Views Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems October 9, 2003 Some.
1 Relational Algebra. 2 Relational Query Languages v Query languages: Allow manipulation and retrieval of data from a database. v Relational model supports.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Relational Algebra.
Relational Calculus Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems September 17, 2007 Some slide content courtesy.
Datalog Inspired by the impedance mismatch in relational databases. Main expressive advantage: recursive queries. More convenient for analysis: papers.
1 Relational Algebra & Calculus Chapter 4, Part A (Relational Algebra)
1 Relational Algebra and Calculas Chapter 4, Part A.
1.1 CAS CS 460/660 Introduction to Database Systems Relational Algebra.
1 Relational Algebra Chapter 4, Sections 4.1 – 4.2.
Chapter 5 Notes. P. 189: Sets, Bags, and Lists To understand the distinction between sets, bags, and lists, remember that a set has unordered elements,
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 4 Relational Algebra.
Database Management Systems, R. Ramakrishnan1 Relational Algebra Module 3, Lecture 1.
Views and XML/Relational Mappings Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems October 21, 2003.
Lu Chaojun, SJTU 1 Extended Relational Algebra. Bag Semantics A relation (in SQL, at least) is really a bag (or multiset). –It may contain the same tuple.
Querying XML, Part II Zachary G. Ives University of Pennsylvania CIS 455 / 555 – Internet and Web Systems February 5, 2008.
 XML derives its strength from a variety of supporting technologies.  Structure and data types: When using XML to exchange data among clients, partners,
XML Schema – XSLT Week 8 Web site:
Extensions of Datalog Wednesday, February 13, 2001.
Lecture 9: Query Complexity Tuesday, January 30, 2001.
XML: Extensible Markup Language
Relational Calculus Zachary G. Ives November 15, 2018
Views and XML Views of Relations
Datalog, View Unfolding, Recursion and Foundations of Integration
XML Views & Reasoning about Views
XML Views & Reasoning about Views
Querying XML: XPath, XQuery, and XSLT
XML Querying and Views Zachary G. Ives November 1, 2007
Querying XML: XQuery and XSLT
Datalog Inspired by the impedance mismatch in relational databases.
Presentation transcript:

XML Views & Reasoning about Views Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems November 3, 2005 Some slide content courtesy of Susan Davidson, Dan Suciu, & Raghu Ramakrishnan

2 Administrivia  Project plans due  Homework 4 deadline extended to tomorrow, Friday, 11/4, 11:59

3 Sorting in XQuery  SQL actually allows you to sort its output, with a special ORDER BY clause (which we haven’t discussed, but which specifies a sort key list)  XQuery borrows this idea  In XQuery, what we order is the sequence of “result tuples” output by the return clause: for $x in document(“dblp.xml”)/proceedings order by $x/title/text() return $x

4 What If Order Doesn’t Matter? By default:  SQL is unordered  XQuery is ordered everywhere!  But unordered queries are much faster to answer XQuery has a way of telling the query engine to avoid preserving order:  unordered { for $x in (mypath) … }

5 Querying & Defining Metadata – Can’t Do This in SQL Can get a node’s name by querying node-name(): for $x in document(“dblp.xml”)/dblp/* return node-name($x) Can construct elements and attributes using computed names: for $x in document(“dblp.xml”)/dblp/*, $year in $x/year, $title in $x/title/text(), element node-name($x) { attribute {“year-” + $year} { $title } }

6 XQuery Conclusions  XQuery is very SQL-like, but in some ways cleaner and more orthogonal  It is based on paths and binding tuples, with collections and trees as its first-class objects  See for more details on the languagewww.w3.org/TR/xquery/

7 A Problem  We frequently want to reference data in a way that differs from the way it’s stored  XML data  HTML, text, etc.  Relational data  XML data  Relational data  Different relational representation  XML data  Different XML representation  Generally, these can all be thought of as different views over the data  A view is a named query  Let’s start with a special presentation language for XML  HTML

8 XSL(T): XML  “Other Stuff”  XSL (XML Stylesheet Language) is actually divided into two parts:  XSL:FO: formatting for XML  XSLT: a special transformation language  We’ll leave XSL:FO for you to read off if you’re interestedwww.w3.org  XSLT is actually able to convert from XML  HTML, which is how many people do their formatting today  Products like Apache Cocoon generally translate XML  HTML on the server side  Your browser will do XML  HTML on the client side

9 A Different Style of Language  XSLT is based on a series of templates that match different parts of an XML document  There’s a policy for what rule or template is applied if more than one matches (it’s not what you’d think!)  XSLT templates can invoke other templates  XSLT templates can be nonterminating (beware!)  XSLT templates are based on XPath “match”es, and we can also apply other templates (potentially to “select”ed XPaths)  Within each template, we describe what should be output  (Matches to text default to outputting it)

10 An XSLT Stylesheet This is DBLP …

11 Results of XSLT Stylesheet Paper1 Smith Chakrabarti Gray Paper2 This Is DBLP Paper1 Smith Paper2 Chakrabarti Gray

12 What XSLT Can and Can’t Do  XSLT is great at converting XML to other formats  XML  diagrams in SVG; HTML; LaTeX  …  XSLT doesn’t do joins (well), it only works on one XML file at a time, and it’s limited in certain respects  It’s not a query language, really  … But it’s a very good formatting language  Most web browsers (post Netscape 4.7x) support XSLT and XSL formatting objects  But most real implementations use XSLT with something like Apache Cocoon – compatible with more browsers  You should use XSL/XSLT to format the forms and pages for your projects – see or the chapter we handed out for more detailswww.w3.org/TR/xslt

13 Views: Alternate Representations XSLT is a language primarily designed from going from XML  non-XML Obviously, we can do XML  XML in XQuery … Or relations  relations … What about relations  XML and XML  relations? Let’s start with XML  XML, relations  relations

14 Views in SQL and XQuery  A view is a named query  We use the name of the view to invoke the query (treating it as if it were the relation it returns) SQL: CREATE VIEW V(A,B,C) AS SELECT A,B,C FROM R WHERE R.A = “123” XQuery: declare function V() as element(content)* { for $r in doc(“R”)/root/tree, $a in $r/a, $b in $r/b, $c in $r/c where $a = “123” return {$a, $b, $c} } SELECT * FROM V, R WHERE V.B = 5 AND V.C = R.C for $v in V()/content, $r in doc(“r”)/root/tree where $v/b = $r/b return $v Using the views:

15 What’s Useful about Views Providing security/access control  We can assign users permissions on different views  Can select or project so we only reveal what we want! Can be used as relations in other queries  Allows the user to query things that make more sense Describe transformations from one schema (the base relations) to another (the output of the view)  The basis of converting from XML to relations or vice versa  This will be incredibly useful in data integration, discussed soon… Allow us to define recursive queries

16 Materialized vs. Virtual Views  A virtual view is a named query that is actually re-computed every time – it is merged with the referencing query CREATE VIEW V(A,B,C) AS SELECT A,B,C FROM R WHERE R.A = “123”  A materialized view is one that is computed once and its results are stored as a table  Think of this as a cached answer  These are incredibly useful!  Techniques exist for using materialized views to answer other queries  Materialized views are the basis of relating tables in different schemas SELECT * FROM V, R WHERE V.B = 5 AND V.C = R.C

17 Views Should Stay Fresh  Views (sometimes called intensional relations) behave, from the perspective of a query language, exactly like base relations (extensional relations)  But there’s an association that should be maintained:  If tuples change in the base relation, they should change in the view (whether it’s materialized or not)  If tuples change in the view, that should reflect in the base relation(s)

18 Views as a Bridge between Data Models A claim we’ve made several times: “XML can’t represent anything that can’t be expressed in in the relational model” If this is true, then we must be able to represent XML in relations Store a relational view of XML (or create an XML view of relations)

19 A View as a Translation between XML and Relations  You have the most-cited paper in this area (Shanmugasundaram et al), and there are many more (Fernandez et al., …)  Techniques already making it into commercial systems  XPERANTO at IBM Research, soon to be DB2 v9  SQL Server 2005 will have XQuery support; Oracle will also shortly have XQuery support  … Now you’ll know how it works!

20 Issues in Mapping Relational  XML  We know the following:  XML is a tree  XML is SEMI-structured  There’s some structured “stuff”  There is some unstructured “stuff”  Issues relate to describing XML structure, particularly parent/child in a relational encoding  Relations are flat  Tuples can be “connected” via foreign-key/primary-key links

21 The Simplest Way to Encode a Tree  Suppose we had: XYZ 14  If we have no IDs, we CREATE values…  BinaryLikeEdge(key, label, type, value, parent) keylabeltypevalueparent 0treeref-- 1contentref-0 2sub- content ref-1 3i-contentref-1 4-strXYZ2 5-int143 What are shortcomings here?

22 Florescu/Kossmann Improved Edge Approach  Consider order, typing; separate the values  Edge(parent, ordinal, label, flag, target)  Vint(vid, value)  Vstring(vid, value) parentordlabelflagtarget -1treeref0 01contentref1 11sub-contentstrv2 11i-contentintv3 vidvalue v314 vidvalue v2XYZ

23 How Do You Compute the XML?  Assume we know the structure of the XML tree (we’ll see how to avoid this later)  We can compute an “XML-like” SQL relation using “outer unions” – we first this technique in XPERANTO  Idea: if we take two non-union-compatible expressions, pad each with NULLs, we can UNION them together  Let’s see how this works…

24 A Relation that Mirrors the XML Hierarchy  Output relation would look like: rLabelridrOrdclabelcidcOrdsLabelsidsOrdstrint tree content sub-content XYZ i-content

25 A Relation that Mirrors the XML Hierarchy  Output relation would look like: rLabelridrOrdclabelcidcOrdsLabelsidsOrdstrint tree content sub-content XYZ i-content

26 A Relation that Mirrors the XML Hierarchy  Output relation would look like: rLabelridrOrdclabelcidcOrdsLabelsidsOrdstrint tree content sub-content XYZ i-content Colors are representative of separate SQL queries…

27 SQL for Outputting XML  For each sub-portion we preserve the keys (target, ord) of the ancestors  Root: select E.label AS rLabel, E.target AS rid, E.ord AS rOrd, null AS cLabel, null AS cid, null AS cOrd, null AS subOrd, null AS sid, null AS str, null AS int from Edge E where parent IS NULL  First-level children: select null AS rLabel, E.target AS rid, E.ord AS rOrd, E1.label AS cLabel, E1.target AS cid, E1.ord AS cOrd, null AS … from Edge E, Edge E1 where E.parent IS NULL AND E.target = E1.parent

28 The Rest of the Queries  Grandchild: select null as rLabel, E.target AS rid, E.ord AS rOrd, null AS cLabel, E1.target AS cid, E1.ord AS cOrd, E2.label as sLabel, E2.target as sid, E2.ord AS sOrd, null as … from Edge E, Edge E1, Edge E2 where E.parent IS NULL AND E.target = E1.parent AND E1.target = E2.parent  Strings: select null as rLabel, E.target AS rid, E.ord AS rOrd, null AS cLabel, E1.target AS cid, E1.ord AS cOrd, null as sLabel, E2.target as sid, E2.ord AS sOrd, Vi.val AS str, null as int from Edge E, Edge E1, Edge E2, Vint Vi where E.parent IS NULL AND E.target = E1.parent AND E1.target = E2.parent AND Vi.vid = E2.target  How would we do integers?

29 Finally…  Union them all together: ( select E.label as rLabel, E.target AS rid, E.ord AS rOrd, … from Edge E where parent IS NULL) UNION ( select null as rLabel, E.target AS rid, E.ord AS rOrd, E1.label AS cLabel, E1.target AS cid, E1.ord AS cOrd, null as … from Edge E, Edge E1 where E.parent IS NULL AND E.target = E1.parent ) UNION (. : ) UNION (. : )  Then another module will add the XML tags, and we’re done!

30 “Inlining” Techniques  Folks at Wisconsin noted we can exploit the “structured” aspects of semi-structured XML  If we’re given a DTD, often the DTD has a lot of required (and often singleton) child elements  Book(title, author*, publisher)  Recall how normalization worked:  Decompose until we have everything in a relation determined by the keys  … But don’t decompose any further than that  Shanmugasundaram et al. try not to decompose XML beyond the point of singleton children

31 Inlining Techniques  Start with DTD, build a graph representing structure tree content sub-content i-content * * * The edges are annotated with ?, * indicating repetition, optionality of children They simplify the DTD to figure this ?

32 Building Schemas  Now, they tried several alternatives that differ in how they handle elements w/multiple ancestors  Can create a separate relation for each path  Can create a single relation for each element  Can try to inline these  For tree examples, these are basically the same  Combine non-set-valued things with parent  Add separate relation for set-valued child elements  Create new keys as needed name book author

33 Schemas for Our Example  TheRoot(rootID)  Content(parentID,  Sub-content(parentID, varchar)  I-content(parentID, int)  If we suddenly changed DTD to <!ELEMENT content(sub-content*, i-content?) what would happen?

34 XQuery to SQL  Inlining method needs external knowledge about the schema  Needs to supply the tags and info not stored in the tables  We can actually directly translate simple XQuery into SQL over the relations – not simply reconstruct the XML

35 An Example for $X in document(“mydoc”)/tree/content where $X/sub-content = “XYZ” return $X  The steps of the path expression are generally joins  … Except that some steps are eliminated by the fact we’ve inlined subelements  Let’s try it over the schema: TheRoot(rootID) Content(parentID, Sub-content(parentID, varchar) I-content(parentID, int)

36 XML Views of Relations  We’ve seen that views are useful things  Allow us to store and refer to the results of a query  We’ve seen an example of a view that changes from XML to relations – and we’ve even seen how such a view can be posed in XQuery and “unfolded” into SQL

37 An Important Set of Questions  Views are incredibly powerful formalisms for describing how data relates: fn: rel  …  rel  rel  Can I define a view recursively?  Why might this be useful? When should the recursion stop?  Suppose we have two views, v 1 and v 2  How do I know whether they represent the same data?  If v 1 is materialized, can we use it to compute v 2 ?  This is fundamental to query optimization and data integration, as we’ll see later

38 Reasoning about Queries and Views  SQL or XQuery are a bit too complex to reason about directly  Some aspects of it make reasoning about SQL queries undecidable  We need an elegant way of describing views (let’s assume a relational model for now)  Should be declarative  Should be less complex than SQL  Doesn’t need to support all of SQL – aggregation, for instance, may be more than we need

39 Let’s Go Back a Few Weeks… Domain Relational Calculus Queries have form: { | p } Predicate: boolean expression over x1,x2, …, xn  We have the following operations:  Rx i op x j x i op constconst op x i  x i. p  x j. p p  q, p  q  p, p  q where op is , , , , ,  and x i,x j,… are domain variables; p,q are predicates  Recall that this captures the same expressiveness as the relational algebra domain variables predicate

40 A Similar Logic-Based Language: Datalog Borrows the flavor of the relational calculus but is a “real” query language  Based on the Prolog logic-programming language  A “datalog program” will be a series of if-then rules (Horn rules) that define relations from predicates  Rules are generally of the form: R out (T 1 )  R 1 (T 2 ), R 2 (T 3 ), …, c(T 2 [ … T n ) where R out is the relation representing the query result, R i are predicates representing relations, c is an expression using arithmetic/boolean predicates over vars, and T i are tuples of variables

41 Datalog Terminology  An example datalog rule: idb(x,y)  r1(x,z), r2(z,y), z < 10  Irrelevant variables can be replaced by _ (anonymous var)  Extensional relations or database schemas (edbs) are relations only occurring in rules’ bodies – these are base relations with “ground facts”  Intensional relations (idbs) appear in the heads – these are basically views  Distinguished variables are the ones output in the head  Ground facts only have constants, e.g., r1(“abc”, 123) headsubgoals body

42 Datalog in Action  As in DRC, the output (head) consists of a tuple for each possible assignment of variables that satisfies the predicate  We typically avoid “ 8 ” in Datalog queries: variables in the body are existential, ranging over all possible values  Multiple rules with the same relation in the head represent a union  We often try to avoid disjunction (“ Ç ”) within rules  Let’s see some examples of datalog queries (which consist of 1 or more rules):  Given Professor(fid, name), Teaches(fid, serno, sem), Courses(serno, cid, desc), Student(sid, name)  Return course names other than CIS 550  Return the names of the teachers of CIS 550  Return the names of all people (professors or students)

43 Datalog is Relationally Complete  We can map RA  Datalog:  Selection  p : p becomes a datalog subgoal  Projection  A : we drop projected-out variables from head  Cross-product r  s: q(A,B,C,D)  r(A,B),s(C,D)  Join r ⋈ s : q(A,B,C,D)  r(A,B),s(C,D), condition  Union r U s: q(A,B)  r(A,B) ; q(C, D) :- s(C,D)  Difference r – s: q(A,B)  r(A,B), : s(A,B)  (If you think about it, DRC  Datalog is even easier)  Great… But then why do we care about Datalog?

44 A Query We Can’t Answer in RA/TRC/DRC… Recall our example of a binary relation for graphs or trees (similar to an XML Edge relation): edge(from, to) If we want to know what nodes are reachable: reachable(F, T) :- edge(F, T)distance 1 reachable(F, T) :- edge(F, X), edge(X, T)dist. 2 reachable(F, T) :- edge(F, X), dist2(X, T)dist. 3 But how about all reachable paths? (Note this was easy in XPath over an XML representation -- //edge) (another way of writing  )

45 Recursive Datalog Queries Define a recursive query in datalog: reachable(F, T) :- edge(F, T)distance 1 reachable(F, T) :- edge(F, X), reachable(X, T)distance >1 What does this mean, exactly, in terms of logic?  There are actually three different (equivalent) definitions of semantics  All make a “closed-world” assumption: facts should exist only if they can be proven true from the input – i.e., assume the DB contains all of the truths out there!

46 Fixpoint Semantics One of the three Datalog models is based on a notion of fixpoint:  We start with an instance of data, then derive all immediate consequences  We repeat as long as we derive new facts In the RA, this requires a while loop!  However, that is too powerful and needs to be restricted  Special case: “inflationary semantics” (which terminates in time polynomial in the size of the database!)

47 Our Query in RA + while (inflationary semantics, no negation) Datalog: reachable(F, T) :- edge(F, T) reachable(F, T) :- edge(F, X), reachable(X, T) RA procedure with while: reachable += edge while change { reachable +=  F, T (  T ! X (edge) ⋈  F ! X (reachable)) }

48 Negation in Datalog Datalog allows for negation in rules  It’s essential for capturing RA set difference-style ops: Professor(, name), : Student(, name)  But negation can be tricky…  … You may recall that in the DRC, we had a notion of “unsafe” queries, and they return here… Single(X)  Person(X), : Married(X,Y)

49 Safe Rules/Queries Range restriction, which requires that every variable:  Occurs at least once in a positive relational predicate in the body,  Or it’s constrained to equal a finite set of values by arithmetic predicates Unsafe: q(X)  r(Y) q(X)  : r(X,X) q(X)  r(X) Ç t(Y) Safe: q(X)  r(X,Y) q(X)  X = 5 q(X)  : r(X,X), s(X) q(X)  r(X) Ç (t(Y),u(X,Y))

50 Negation and Recursion  Unfortunately, the fixpoint semantics we mentioned previously for recursion “breaks” with negation…  q(x)  : q(x)No fixpoint!  p(x)  : q(x)Multiple minimal fixpoints! q(x)  : p(x)  Or the fixpoint may not “converge” (or converge to a minimal fixpoint)  This is all bad news…

51 One Way to Fix Things: Stratified Semantics  Start with semipositive datalog: negation only over edb predicates  From here, we can compute a set of values for the idb predicates that depend on the edb’s  Now we can “materialize” the results of the first set of idbs; we’ll remove their rules and treat them as edbs to compute a next “stratum” r (1,1) r (1,2) s (1,1) v1(x,y) :- r(x,y), : s(x,y) q(x,y) :- v1(x,y), : s(x,y) r (1,1) r (1,2) s (1,1) v1 (1,2) q(x,y) :- v1(x,y), : s(x,y) r (1,1) r (1,2) s (1,1) v1 (1,2) q (1,2)

52 Precedence Graphs  Take a set of datalog rules, create a node for each relation (edb or idb)  If r  r’ then add an edge labeled “+” from r to r’  If r  : r’ then add an edge labeled “-” from r to r’  We can stratify if there are no cycles with “-” edges v1(x,y) :- r(x,y), : s(x,y) q(x,y) :- v1(x,y), : s(x,y) s r v1 q - + +

53 Stratifying Datalog Execution foreach predicate p, set stratum(p) = 1 do until no change, or some stratum > # of predicates foreach rule h  b { foreach negated subgoal of b with predicate q { stratum(p) = max(stratum(p), 1+stratum(q)) } foreach positive subgoal of b with predicate q { stratum(p) = max(stratum(p), stratum(q) }

54 Conjunctive Queries A single Datalog rule with no “ Ç,” “ :,” “ 8 ” can express select, project, and join – a conjunctive query  Conjunctive queries are possible to reason about statically  (Note that we can write CQ’s in other languages, e.g., SQL!) We know how to “minimize” conjunctive queries An important simplification that can’t be done for general SQL We can test whether one conjunctive query’s answers always contain another conjunctive query’s answers (for ANY instance)  Why might this be useful?

55 Example of Containment Suppose we have two queries: q1(S,C) :- Student(S, N), Takes(S, C), Course(C, X), inCSE(C), Course(C, “DB & Info Systems”) q2(S,C) :- Student(S, N), Takes(S, C), Course(C, X) Intuitively, q1 must contain the same or fewer answers vs. q2:  It has all of the same conditions, except one extra conjunction (i.e., it’s more restricted)  There’s no union or any other way it can add more data We can say that q2 contains q1 because this holds for any instance of our DB {Student, Takes, Course}

56 Checking Containment via Canonical DBs  To test for q1 µ q2:  Create a “canonical DB” that contains a tuple for each subgoal in q1  Execute q2 over it  If q2 returns a tuple that matches the head of q1, then q1 µ q2 (This is an NP-complete algorithm in the size of the query. Testing for full first-order logic queries is undecidable!!!)  Let’s see this for our example…

57 Example Canonical DB  q1(S,C) :- Student(S, N), Takes(S, C), Course(C, X), inCSE(C), Course(C, “DB & Info Systems”)  q2(S,C) :- Student(S, N), Takes(S, C), Course(C, X) StudentTakesCourseinCSE SN SC CX CDB & Info Systems S Need to get tuple in executing q2 over this database

58 Wrapping up… We’ve seen a new language, Datalog  It’s basically a glorified DRC with a special feature, recursion  It’s much cleaner than SQL for reasoning about  … But negation (as in the DRC) poses some challenges We’ve seen that a particular kind of query, the conjunctive query, is written naturally in Datalog  Conjunctive queries are possible to reason about  We saw an example of testing for containment  Next time we’ll see some further examples