|
Helping ordinary people create extraordinary websites! |
Make Database Queries Without the DatabaseBy Brian Goetz2005-07-14
XQuery to the rescue The other data query alternative that was easily available was XQuery. XQuery has the advantage that it is designed for producing XML or HTML documents as the result of its queries, so no postprocessing would be required on query results. This idea was attractive -- only one layer of coding for each report, rather than two or more. So the first task was to build an XML document that represented the whole data set. It was straightforward to design a simple XML data model and to write a Visitor that traversed the data structure and appended each element to a DOM Document. (There was never a need to write this document out. It could be kept in memory for querying and then discarded when finished. When the underlying data changed, it could simply be regenerated.) Then all that was needed was to write XQuery queries, which would both select and aggregate the data for the report, and format them into the final desired format (XML or HTML). The queries could be stored in separate files for rapid prototyping and so that multiple report formats could be supported. The code to evaluate the query using Saxon is shown in Listing 4: Listing 4. Code to execute XQuery query and serialize results to an XML or HTML document
The structure of the XML document representing the database was a little different from the in-memory data structure; each <site> element had nested <page> elements, each <page> element had nested <link> elements, and each <link> element had <link-to> and <link-from> elements. This representation turned out to be convenient enough for most reports. Listing 5 shows a sample XQuery report that handles selection of links, sorting, and presentation. It has several advantages over the Visitor approach -- not only is it less code (because the query language supports selection, aggregation, and sorting), but all the code for the report -- selection, aggregation, sorting, and presentation -- is in one place. Listing 5. XQuery code that produces the entire most-linked-pages report
Tutorial Pages: » Borrowing a data model can simplify development and enhance performance » No database needed » My kingdom for a data model » XQuery to the rescue » Summary » Resources First published by IBM developerWorks |
|