Home

ODMG OQL User Manual

image

Contents

1. where e name like Sp This names the result of the query and not the query itself The name MyEmployees can then be used in other queries Named queries greatly improve the legibility of complex queries 30 ODMG OQL User Manual Operators Element Note Element Exists You can only reuse these named queries in the same query session i e up toacommit or abort point When you have a set or a bag that contains a single element you extract the element directly using the element operator For example element select e from e in Globe employees where e name Tintin This query gives the result You can add a new persistent name to cover all the different companies that exist name TheCompanies list Company You can now carry out more complex queries such as selecting which company has at least one employee under the age of 23 select c name from c in TheCompanies where exists e in c employees e age lt 23 ODMG OQL User Manual 31 2 Getting Started Group by The answer is a bag of names The International G The Daily News The Telegraph This operator groups together objects of a collection with the same value for particular attributes For example select from e in Globe employees group by e salary This groups the employees by salary giving a bag of two attribute tuples 32 ODMG OQL User Manual Op
2. 2 3 Constructing results The structure of a query result is very often implicit For example when you extract the age field of an employee which is of type integer you obtain an integer When you filter a set bag or list you obtain a set bag or list depending on what you select However you can also construct a query result with an explicit structure using the struct set bag list and array constructors For example using the struct constructor select struct employee e name position e position salary e salary from e in Globe employees or simply select e name e position e salary from e in Globe employees This query gives the name position and salary of the employees at the International Globe newspaper ODMG OQL User Manual 27 Getting Started of ahell You can use the special operator to select all attributes of the elements of a collection For example select from Globe employees Note that in this example you do not need to define a variable with from You can also build up embedded structures simply by combining struct operators For example to get the identities and salaries of all those employees working as reporters and older than 22 select struct employee struct name e name age e age salary e salary from e in Globe employees where e position Reporter and e age gt 22
3. ODMG OQL User Manual 5 0 April 1998 Information in this document is subject to change without notice and should not be construed as a commitment by Oo Technology The software described in this document is delivered under a license or nondisclosure agreement The software can only be used or copied in accordance with the terms of the agreement It is against the law to copy this software to magnetic tape disk or any other medium for any purpose other than the purchaser s own use Copyright 1992 1998 Os Technology All rights reserved No part of this publication can be reproduced stored in a retrieval system or transmitted in any form or by any means electronic mechanical photocopy without prior written permission of O2 Technology Oo OoEngine API O2C OoDBAccess OoEngine OoGraph OoKit Oo2Look OoStore O2Tools and O2Web are registered trademarks of Oo Technology SQL and AIX are registered trademarks of International Business Machines Corporation Sun SunOS and SOLARIS are registered trademarks of Sun Microsystems Inc X Window System is a registered trademark of the Massachusetts Institute of Technology Unix is aregistered trademark of Unix System Laboratories Inc HPUX is a registered trademark of Hewlett Packard Company BOSX is a registered trademark of Bull S A IRIX is a registered trademark of Siemens Nixdorf A G NeXTStep is a registered trademark of the NeXT Computer Inc Purify
4. 28 ODMG OQL User Manual Constructing results Creating an object This query gives a bag with one element Creating an object You create values using struct list array bag and set In OQL you can also create objects using the class name and by initializing the attributes of your choice Any un initialized attributes are set to the default value For example to create an object of the class Client Client name Trent This creates atemporary object with the name attribute initialized to Trent You can then make the object persistent in the usual way refer to the OoC C and Java manuals The result of this query is the new object An object collection can be created in the same way For example use the following query to create an 02_list_Client collection o2 list Client list Client name John Client name Jack ODMG OQL User Manual 29 2 Getting Started 2 4 Operators Count Define This section outlines the basic OQL operators you can use to query the database You can query the database using the count clause For example to find out how many employees there are at the International Globe newspaper count Globe employees This query returns an integer Other aggregate operators are min max sum and avg You can name the result of a query using the define clause For example define MyEmployees as select e from e in Globe employees
5. ODMG OQL User Manual 41 2 Getting Started 42 ODMG OQL User Manual 3 OQL Rationale Most commercial object database systems now have a common data model based on the OMG object model This data model is defined in the ODMG 93 report Based on this ODMG model the query language OQL was defined and adopted by the ODMG group This chapter is divided as follows e The ODMG standard e The ODMG model e OQL by example ODMG OQL User Manual 43 3 OQL Rationale 3 1 The ODMG standard The ODMG standard covers the following points 1 an object model 2 an object definition language for this model with its own syntax ODL or its expression through C and Smalltalk syntax 3 an object query language for this model OQL 4 a C binding allowing C programs to operate on a database compliant to the object model 5 a Java binding allowing Java programs to operate on a database compliant to the object model 3 2 The ODMG model The ODMG object model supports the notion of classes of objects with attributes and methods of inheritance and specialization It offers the classical types to deal with string date time time interval and timestamp And finally it supports the notions of relationships and collections ODMG 93 introduces a set of predefined generic collection classes Set lt T gt Bag lt T gt a multi set i e a set with repeated elements Varray lt T gt a variable si
6. The select from where clause enables you to extract those elements meeting a specific condition from a collection Os collections include set bag a multi set or set with duplicates list an insertable and dynamic array or array The OQL query has the following structure select defines the structure of the query result from introduces the collections against which the query runs where introduces a predicate that filters the collection This section now describes how to use this clause A set is a non ordered collection The most frequent query on a set is a filter This consists of extracting the elements of a set which have certain characteristics 22 ODMG OQL User Manual Select from where Set For example select e from e in Globe employees where e salary gt 200 00 This query returns those employees working at the International Globe with a salary over 200 The select clause defines the query result as the employees and the from Clause gives the set on which to run the query The variable e represents each of its elements in turn The where clause filters the employees so that those earning more than 200 are extracted This query therefore builds a collection of employees This collection is in fact a bag as duplicates are accepted You can also add the keyword distinct to eliminate any duplicates from the resulting bag and then produce a true set Moreover you can access fr
7. necessary condition for an efficient query optimizer When a polymorphic collection is filtered for instance Persons its elements are statically known to be of that class for instance Person This means that a property of a subclass attribute or method cannot be applied to such an element except in two important cases late binding to a method or explicit class indication e Late binding To list the activities of each person we use the following query select p activities from p in Persons ODMG OQL User Manual 53 3 OQL Rationale activities is a method which has 3 incarnations one for Student one for Employee and one for generic Person Depending on the kind of person of the current p the right incarnation is called Class indicator To go down theclass hierarchy a user may explicitly declare the class of an object that cannot be inferred statically The interpreter then has to check at runtime that this object actually belongs to the indicated class or one of its subclasses For example assuming we know that only students spend their time in following a course of study we can select those persons and get their grade We explicitly indicate in the query that these persons are students select Student p grade from p in Persons where course of study in p activities Operator composition OQL is a purely functional language all operators can be composed freely as long as the t
8. In an Oo database named objects and values can either be values of any type or objects of any class Consequently OQL allows you to query values or objects of any type or class Note The query results shown below are all given in the Unix graphic form Simple queries Simple queries can involve different types of values e Atomic values With atomic values you can carry out arithmetic calculations e g Pee2 This is a query which returns the integer 4 20 ODMG OQL User Manual Basic queries Simple queries e Struct values You can also consider the value of the object Globe of class Company as a struct or tuple value with three attributes The only operation you can carry out on a struct is extracting a field e g This returns the name of the Globe Company e List or array values A list is an ordered collection that allows duplicates and you can therefore extract any of its elements if you Know their position For example you can extract the first element of the list in clients as follows Globe clients 0 In OQL you count list elements from 0 For OQL an array behaves the same way as a list ODMG OQL User Manual 21 2 Getting Started Set e Call of a method To apply a method to an object is a base query e g Globe title This applies the method title to the object Globe and returns the result of the method title 2 2 Select from where
9. Select Expression see Sections 4 3 8 4 3 9 4 3 10 query select distinct projection_attributes from variable declaration variable declaration where query group by partition_attributes having query order by sort_criterion sort_criterion projection_attributes projection projection projection_attributes projection query projection identifier query projection query aS identifier query as identifier variable declaration partition_attributes projection projection sort_criterion query ordering ordering asc ordering desc Set Expression see Section 4 3 12 query query intersect query query query union query query query except query Conversion see Section 4 3 13 query listtoset query query element query query distinct e query flatten query query class_name query Operator Priorities The following operators are sorted by decreasing priority Operators on the same line have the same priority and group left to right 0 gt 88 ODMG OQL User Manual OQL BNF Operator Priorities not unary unary In mod intersect union except lt gt lt gt lt some lt any lt all etc for all comparison operators l like and exists for all or identifier this is the cast operator order having group by where from select ODMG OQL User Ma
10. after the grammar Some syntactical ambiguities are solved semantically from the types of the operands ODMG OQL User Manual 85 4 5 1 4 5 1 1 4 5 1 2 4 5 1 3 4 5 1 4 Grammar Axiom see Sections 4 3 1 4 3 2 query program define_query query define query define identifier aS query Basic see Section 4 3 3 query nil query true query false query integer_literal query float_literal query character_literal query string_literal query entry_name query query name query bind argument query from_variable_ name query query Simple Expression see Section 4 3 5 query query query query query query query query query query query query query query query query mod query query abs query query query query Comparison see Section 4 3 5 query query comparison_operator query query query like string_literal comparison_operator comparison_operator comparison_operator gt comparison_operator lt comparison_operator gt 1 A bind argument allows to bind expressions from a programming language to a query when embedded into this language see Chapters on language bindings 2 The operator is also used for list and array concatenation 86 ODMG OQL User Manual OQL BNF Grammar 4 5 1 5 4 5 1 6 4 5 1 7 4 5 1 8 comparison_operato
11. an atomic type void marriage d_Ref lt Person gt spouse This person gets a spouse void birth d_Ref lt Person gt child This person gets a child d Set lt d_Ref lt Person gt gt ancestors Set of ancestors of this Person virtual d_Set lt d_String gt activities j A redefinable method class Employee Person A subclass of Person float salary Method virtual d_Set lt d_String gt activities j This method is redefined 46 ODMG OQL User Manual The ODMG model class Student Person A subclass of Person d_String grade Method virtual d_Set lt d_String gt activities j The method is redefined ODMG OQL User Manual 47 OQL Rationale class Address int number d_String street L class Building Address address A complex value Address embedded in this object d_List lt lt d_Ref lt Apartment gt gt apartments inverse building Method d_Ref lt Apartment gt less_expensive class Apartment int number d_Ref lt Building gt building d_Ref lt Person gt is_used_by inverse lives_in d Ref lt Person gt gt Persons All persons and employees d_Ref lt Apartment gt gt Apartments The Apartement class extent d_Ref lt Apartment gt gt Vacancy The set of vacant appartements d_List lt d_Ref lt Apartment gt gt Directory Thelist of appartements ordered by their number of rooms 4
12. be composed as soon as the operands respect the type system This isa consequence of the fact that the result of any query has a type which belongs to the ODMG type model and thus can be queried again OQL is not computationally complete It is an easy to use query language which provides easy access to an object database Based on the same type system OQL can be invoked directly from within programming languages for which an ODMG binding is defined e g C Conversely OQL can invoke operations programmed in these languages OQL does not provide explicit update operators but rather can invoke operations defined on objects for that purpose and thus does not breach the semantics of an Object Database which by definition is managed by the methods defined on the objects OQL provides declarative access to objects Thus OQL queries can be easily optimized by virtue of this declarative nature The formal semantics of OQL can easily be defined 58 ODMG OQL User Manual Language Definition Query Program 4 3 4 3 1 Language Definition OQL is an expression language A query expression is built from typed operands composed recursively by operators We will use the term expression to designate a valid query in this section Query Program A query program consists of a possibly empty set of query definition expressions followed by an expression which is evaluated as the query itself The set of query def
13. col and the result is col lt t gt which is thus a list resp an array Of course duplicates if any are maintained by this operation e If col is a list or an array and col is a set or a bag the lists or arrays are converted into sets the union of all these sets is done and the result is a set lt t gt therefore without duplicates Examples flatten list set 1 2 3 set 3 4 5 6 set 7 This returns the set containing 1 2 3 4 5 6 7 flatten list list 1 2 list 1 2 3 This returns list 1 2 1 2 3 flatten set list 1 2 list 1 2 3 ODMG OQL User Manual 79 4 3 13 5 4 3 14 4 3 15 This returns the set containing 1 2 3 Typing an Expression Ife is an expression ifcisatypename then c eis an expression This asserts that e is an object of class type ce If it turns out that it is not true an exception is raised at runtime This is useful to access a property of an object which is statically known to be of a superclass of the specified class Example select Employee s salary from Students s where s in select sec assistant from Sections sec This returns the set of salaries of all students who are teaching assistants assuming that Students and Sections are the extents of the classes Student and Section Function Call If fis a function name ife e e are expressions then and f f el e2 en are expressions whose value is the value
14. distinct e salary from e in Globe employees where e name like Sp returns the salaries of all enployees whose names begin with Sp 238 000000 40 000000 You can obtain a sorted list using the order by clause For example to sort the employees by name and by age select e from e in Globe employees order by e name e age The result of an order by operation is always a list even though the source of the objects to sort the set employees in this case may bea Set This query returns a list of employees their order is alphabetical by name and then by age ODMG OQL User Manual 35 2 Getting Started 2 5 Set operators The standard set operations are defined on set and bag union intersect intersection and except difference You can also write these operators as union intersection and difference You can define another query YourEmployees define YourEmployees as select e from e in Globe employees where e name Tintin Now you can combine the queries by adding together two sets MyEmployees YourEmployees The simple addition union of the two sets of employees gives you a set containing the answer 36 ODMG OQL User Manual Conversions The pick operator is defined on a set or a bag It returns an element of the collection chosen arbitrarily For example pick MyEmployees 2 6 Conversions List to set To convert a list o
15. nil objects when they are encountered If a path expression contains a nil object a predicate is always considered false This means that the previous expression can be rewritten as follows select c name from c in Globe clients where count c order List or array A list or an array is an ordered collection that can contain duplicate elements Since it is ordered you may extract any of its elements if you know their position For example Globe clients 2 This extracts the third element of the list the first element is at position 0 As with sets you can filter a list ODMG OQL User Manual 25 2 Getting Started For example what are the names of the clients who buy the International Globe newspaper select e name from e in Globe clients The result of this query is a bag of the name of Globe clients Note The query returns a bag and not alist Toreturn alist you must define an order See Order by on page 35 You can also add the keyword distinct toa selection to eliminate any duplicates from the resulting set Note You can manipulate very complex structures A list can be made up of tuples which in turn can have a set attribute etc Consequently you have access to all the embedded components of an object For more details refer to Section 2 3 for constructing query results and Section 2 7 for combining operators 26 ODMG OQL User Manual Constructing results
16. of the class Person No attribute of the class Person can be accessed directly since they are ambiguous between child and Persons In scope3 we see the names age partition and the same names from scopel except age and partition if they exist In scope4 we see the names age partition p v and the same names from scopel except age partition p and v if they exist In scope5 we see the names p and the same names from scope except p if it exists In scope6 we see the names p v Persons c Cities the property names of the class City which are not property of the class Person No attribute of the class Person can be accessed directly since they are ambiguous between child and Persons Os note Implicit attribute scope is not available with O2 You must always access an attribute with the dot notation v att 4 4 Syntactical Abbreviations OQL defines an orthogonal expression language in the sense that all operators can be composed with each others as soon as the types of the operands are correct To achieve this property we have defined a functional language with simple like or composite operators like select from where group_by order_by which always deliver a result in the same type system and which thus can be recursively operated with other operations in the same query In order to accept the whole DML query part of SQL as a valid syntax for OQL OQL is added some ad hoc construc
17. of the object oriented query language OQL Oo is a revolutionary system that is particularly well adapted for developing large scale client server applications in both fields of business and technical software development This chapter introduces the Os system and the OQL query language The chapter is divided into the following sections e System Overview e Interactive and embedded query language e Manual overview ODMG OQL User Manual 1 Introduction 1 1 System Ove rview The system arch Development Tools O Dev Tools Database Engine Figure 1 1 Oo System Archite itecture of Oo is illustrated in Figure 1 1 gt a Interfaces Standard Dev Tools Oz O Corba ODB Access O Engine O Store Giaa cture The Oo system can be viewed as consisting of three components The Database Engine provides all the features of a Database system and an object oriented system This engine is accessed with Development Tools such as various programming languages Op development tools and any standard development tool Numerous External Interfaces are provided All encompassing O2 is a versatile portable distributed high performance dyn amic object oriented database system Database Engine e OoStore e OoEngine The database management system provides low level facilities through Oo2Store API to access and managea database disk volumes files records indices and transac
18. the ODMG standard with notes added on how to use this language with Oo 1 The Object Database Standard ODMG 93 Atwood Duhl Ferran Loomis and Wade Edited by R G G Cattell 1996 Morgan Kaufman Publishers ODMG OQL User Manual 57 4 1 4 2 Introduction In this chapter a formal and complete definition of the language is given For each feature of the language we give the syntax its semantics and an example Alternate syntax for some features are described in Section 4 4 which completes OQL in order to accept any syntactical form of SQL The chapter ends with the formal syntax which is given in Section 4 5 Principles Our design is based on the following principles and assumptions OQL relies on the ODMG object model OQL is a superset of the standard SQL part which allows you to query a database Thus any select SQL sentence which runs on relational tables works with the same syntax and semantics on collections of ODMG objects Extensions concern Object Oriented notions like complex objects object identity path expression polymorphism operation invocation late binding etc OQL provides high level primitives to deal with sets of objects but does not restrict its attention to this collection construct Thus it also provides primitives to deal with structures lists arrays and treats all such constructs with the same efficiency OQL is a functional language where operators can freely
19. the children of each person along with the address of this person we use the following query select struct me p name my address p lives_in building address my children select struct name c name address c lives_in building address from c in p children from p in Persons ODMG OQL User Manual 51 3 OQL Rationale This gives for each person the name the address and the name and address of each child The type of the result is a bag of the following struct struct String me Address my_address Bag lt struct String name Address address gt my_children OQL can also create complex objects For this purpose it uses the name of a class as a constructor Attributes of the object of this class can be initialized explicitly by any valid expression For instance to create a new building with 2 apartments if thereisa type name in the schema called List_apart defined by tydedef List lt lt Ref lt Apartment gt gt List_apart the query is Building address Address number 10 street Main street apartments List_apart list Apartment number 1 Apartment number 2 Method invoking OQL allows method calls with or without parameters anywhere the result type of the method matches the expected type in the query In case the method has no parameter the syntax for method call is the same as for accessing an attribute or traversing a relationsh
20. 8 ODMG OQL User Manual OQL by example Path expressions 3 3 OQL by example Let us now turn to an example based presentation of OQL We use the database described in the previous section and instead of trying to be exhaustive we give an overview of the most relevant features Path expressions As explained above one can enter a database through a named object but more generally as soon as one gets an object which comes for instance from a C expression one needs a way to navigate from it and reach the right data one needs Todo this in OQL weusethe or indifferently gt notation which enables us to go inside complex objects as well as to follow simple relationships For instance given a Person p to know the name of the street where this person lives we use the following OQL query p lives_in building adddress street This query starts from a Person traverses an Apartment arrives in a Building and goes inside the complex attribute of type Address to get the street name This example treated 1 1 relationship let us now look at n p relationships Assume we want the names of the children of the person p We cannot write p children name because children is a List of references so the interpretation of the result of this query would be undefined Intuitively the result should be a collection of names but we need an unambiguous notation to traverse such a multiple relationship and we use th
21. Manual 75 4 3 11 3 4 3 11 4 Example element select x from Courses x where x name math and x number 101 requires 0 2 This returns the list consisting of the first three prerequisites of Math 101 Getting the First and Last Elements of an Indexed Collection If eis an expression if lt op gt is an operator from first last eisa list or an array then lt op gt e is an expression This extracts the first and last element of a collection Example first element select x from Courses x where x name math and x number 101 requires This returns the first prerequisite of Math 101 Concatenating Two Indexed Collections If e and e are expressions if e and e are both lists or both arrays then e e is an expression This computes the concatenation of e and ez Example list 1 2 list 2 3 This query generates list 1 2 2 3 76 ODMG OQL User Manual Language Definition Binary Set Expressions 4 3 12 Binary Set Expressions 4 3 12 1 Union Intersection Difference If e and e are expressions if lt op gt is an operator from union except intersect Ife and e are sets or bags then eu lt op gt e is an expression This computes set theoretic operations union difference and intersection on e and es as defined in Chapter 2 When thecollection kinds of the operands aredifferent bag and set the set is converted into a bag beforehan
22. Quantify are registered trademarks of Pure Software Inc Windows is a registered trademark of Microsoft Corporation All other company or product names quoted are trademarks or registered trademarks of their respective trademark holders Who should read this manual OQL is an object oriented SQL like query language the ODMG standard This manual describes how to use OQL as an embedded function in a programming language e g O2C C C or Java or interactively as a query language It assumes previous knowledge of the Oo system Other documents available are outlined click below See O2 Documentation set SE Technology TABLE OF CONTENTS This manual is divided into the following chapters 1 Introduction 2 Getting Started 3 OQL Rationale 4 OQL Reference ODMG OQL User Manual TABLE OF CONTENTS Introduction 9 N e n seisin eaaa 10 E E E EAE AE 12 ativan reverent antacid eens 12 1 2 Interactive and embedded query language cssss000 14 rane 15 KT a Ea 6 TTT 15 Lo Mantal SIG ao 16 Getting Started 17 21 BASIC 2 0 lt 1 jase see eee eee 18 Database eniry POLITS TT 20 Oe e Do EREET EEA EEE I E TEE OE E T E 20 2 2 Select from where ssssssnssnnnnnnunennennnnnnnnennnnnnnnnnnnn nnmnnn nne 22 E e PETEA ET A FEE EAEE S EEN EENAA esd ees EA iL ii DTE 24 N alm op OE 24 i ne 25 Fe TTT 2 3 Constructing results sss sss sss ssss sss ss esse seene nene
23. and eu e gt ep are expressions then t p e Pn en iS an expression This defines a new object of type t whose properties p po Phn are initialized with the expressions eu ea e Thetype of e must be compatible with the type of p Ift is atype name of a collection and e is a collection literal then t e is a collection object The type of e must be compatible with t Examples Employee name Peter boss Chairman This creates a mutable Employee object ODMG OQL User Manual 61 4 3 4 2 4 3 4 3 4 3 4 4 vectint set 1 3 10 This creates a mutable set object assuming that vectint is the name of a Class whose type is Bag lt int gt Constructing Structures If P1 Po Py are property names and eu e5 e are expressions then struct p eu Po G9 Pr n is an expression It defines the structuretaking valuese e5 u on properties p4 Po Py Note that this dynamically creates an instance of the type struct p ti Po to Pp tn if t is the type of e Example struct name Peter age 25 This returns a structure with two attributes name and age taking respective values Peter and 25 See also abbreviated syntax in some contexts in Section 4 4 1 Constructing Sets If eu ear e pare expressions then set e e5 e isan expression It defines the set containingtheelementse e gt e It creates a set in
24. ay index query allows you to see how OQL will use existing indexes in que ries you will make To stop this feature execute display index again Note Please refer to the System Administration Guide for details on how to create and manage indexes ODMG OQL User Manual Chapter Summary Display index 2 9 Chapter Summary This chapter has covered the following points Basic queries To query any database you need various entry points In Oo these are the named instances i e named objects and named values Simple queries include calling an entry point applying a method toa named object extracting a field etc Select from where The select from where clause enables you to extract those elements meeting a specific condition from a list or set Constructing results The structure of a query result is very often implicit However you can also construct a query result with an explicit structure using the struct set and list constructors Operators OQL operators include define element order by count exists group by and like They can be combined for complex queries Indexes When OQL extracts one or more elements from a set or list it scans the whole collection to find the desired elements You can improve performance if you tell the system exactly where to look This is done by establishing an index on acollection An index maps a key to oneor more elements of a named collection
25. button removes the graphical result This query result consists of anumber of objects Each object has its own pop up menu which is displayed by clicking the Object icon using the right mouse button This pop up menu can be used to access the public methods of each object Windows NT In Windows NT the query result is displayed in a window in textual form containing hypertext links Each link represents a sub object The label for a specific link may be obtained by applying the title method to the sub object represented by the link Clicking on a hypertext link with the right mouse button replaces the contents of the window with a representation of the sub object associated with the link Figure 1 3 shows atypical query result in graphical form as generated in Windows NT ODMG OQL User Manual 13 al Introduction oey nom Joseph age 30 Bpoux Person an Figure 1 3 Typical OQL query result in graphical form as generated in Windows NT The browser shown in Figure 1 3 has the following buttons Back this button displays the previous object Forward this button displays the next sub object It is only valid if the Back button has been activated at least once New Window This button displays the current object in a new window Each window is an independent browser Quit This button closes the active window The query result is an object of the Person class which has a name an age and a spo
26. ct nil if the operation returns nothing Example jones gt number_of_students This applies the operation number ot students to jones 4 3 6 5 Applying an Operation with Parameters to an Object Ife is an expression ife e are expressions if fis an operation name then e gt f e e e and e f e amp e are expressions that apply operation with parameterse e e to object e The value of the expression is the one returned by the operation or else the object nil if the operation returns nothing In both cases if e happens to designate a deleted or anon existing object i e nil an attempt to apply an operation to it raises an exception ODMG OQL User Manual 67 However a query may test explicitly if an object is different from nil before applying an operation Example Doe gt apply_course Maths Turing gt number This query calls the operation apply course on class Student for the object Doe It passes two parameters a string and an object of class Professor The operation returns an object of type Course and the query returns the number of this course 4 3 6 6 Dereferencing an Object If eis an expression which denotes an object with identity a mutable object then eis an expression which delivers the value of the object a literal Example Given two variables of type Person p1 and p2 the predicate pl p2 is true if both variables refer to the same ob
27. d and the result is a bag Examples Student except Ta This returns the set of students who are not Teaching Assistants bag 2 2 3 3 3 union bag 2 3 3 3 This bag expression returns bag 2 2 3 3 3 2 3 3 3 bag 2 2 3 3 intersect bag 2 3 3 3 The intersection of 2 bags yields a bag that contains the minimum for each of the multiply values So the result is bag 2 3 3 bag 2 2 3 3 3 except bag 2 3 3 3 This bag expression returns bag 2 4 3 12 2 Inclusion If e and e are expressions which denote sets or bags if lt op gt is an operator from lt lt gt gt then eu lt op gt e is an expression whose value is a boolean When the operands are different kinds of collections bag and set the set is first converted into a bag ODMG OQL User Manual TI 4 3 13 4 3 13 1 4 3 13 2 eu lt e is true if e is included into e but not equal to e eu lt e is trueif e is included into e Example set 1 2 3 lt set 3 4 2 1 is true Conversion Expressions Extracting the Element of a Singleton If e is a collection valued expression element e is an expression This takes the singleton e and returns its element If e is not a singleton this raises an exception Example element select x from Professors x where x name Turing This returns the professor whose name is Turing if there is only one Turning a List into a Set If eis alist expres
28. e select from where clauseto handle collections just as in SQL select c name from c in p children The result of this query is a value of type Bag lt String gt If we want to get a Set we simply drop duplicates like in SQL by using the distinct keyword select distinct c name from c in p children ODMG OQL User Manual 49 3 OQL Rationale Now we have a means to navigate from any object to any other object following any relationship and entering any complex subvalues of an object For instance we want the set of addresses of the children of each Person of the database We know the collection named Persons contains all the persons of the database We have now to traverse two collections Persons and Person children Like in SQL the select from operator allows us to query more than one collection These collections then appear in the from part In OQL a collection in the from part can be derived from a previous one by following a path which starts from it and the answer is select c lives_in building address from p in Persons c in p children This query inspects all children of all persons Its result is of the type Bag lt Address gt Predicate Of course the where clause can be used to define any predicate which then serves to select the data matching the predicate For instance to restrict the previous result to the people living on Main Street and having at least 2 children who do no
29. each of which has a property called partition which contains the bag of employees that enter in this category So the type of the result is set lt struct low boolean medium boolean high boolean partition bag lt struct e Employee gt gt The second form enhances the first one with a having clause which enables you to filter the result using aggregative functions which operate on each partition ODMG OQL User Manual 73 Example select department avg_salary avg select p e salary from partition p from Employees e group by department e deptno having avg select p e salary from partition p gt 30000 This gives a set of couples department and average of the salaries of the employees working in this department when this average is more than 30000 So the type of the result is bag lt struct department integer avg_salary float gt Oo note 4 3 10 In Oo the syntax of partition_attributes does not accept the keyword struct and thus is always given as a list of criteria separated by commas See Section 4 4 1 Order by Operator If select_query is a select from where or a select from where group_ by query and if eu ear e are expressions then select_query order by ej eac u is an expression It returns a list of the selected elements sorted by the function e and inside each subset yieldingthesamee sorted by e lt and the final subsub set sorted by e Example
30. ed instead of D Control D Embedded OQL Any valid query can be passed from O2C code to OQL using the system supplied function o2query This is detailed in the OoC Reference manual Similarly you can pass a query to a C C Smalltalk or Java program Refer to the respective manuals for details ODMG OQL User Manual 15 a Introduction 1 3 Finally an OQL function exists in O2Engine and is described in the OsEngine API Reference Manual Manual overview This manual is divided up into the following chapters Chapter 1 Introduction This chapter introduces the Op system and the OQL query language It outlines the concepts of the ad hoc query language that allows you to browse the database quickly and efficiently to get the information you want and the embedded query language that you can call from inside your programs Chapter 2 OQL Getting started This chapter introduces the OQL language so you can start to use OQL in order to obtain the exact information you want from your database It describes and illustrates basic and select from where queries details how to construct results and describes the use of operators and indexes To fully understand this chapter you must know the ODMG data model Chapter 3 OQL Rationale This chapter introduces the ODMG standard and describes the ODMG object model It also gives an example based presentation of OQL Chapter 4 OQL Reference This c
31. edefined classes and methods for faster development of user applications Complete graphical programming environment to design and develop Oo database applications Standard Development Tools All standard programming languages can be used with standard environments e g Visual C Sun Sparcworks External Interfaces e OoCorba e OoDBAccess e OoODBC OoWeb Create an Oo Orbix server to access an Oo database with CORBA Connect Os applications to relational databases on remote hosts and invoke SQL statements Connect remote ODBC client applications to Oo databases Create an Oo World Wide Web server to access an Oo database through the internet network ODMG OQL User Manual 11 1 Introduction OQL OQL is an object oriented SQL like query language OQL is the query language of the ODMG 93 standard It can be used in two different ways either as an embedded function in a programming language or as an ad hoc query language You can use OQL as a function called from OoC C C Smalltalk or Java in order to manipulate complex values and methods Each construct produces a result which can then be used directly in the programming language Methods can be triggered to modify the database You will find that programming is easier because OQL can filter values using complex predicates whose evaluations are optimized by the OQL optimizer in Oo OQL can also be used interactively as an ad hoc query lan
32. erators Group by IS m The first attribute is the salary and is called salary as specified The second is the set of objects employees with the same salary and is called partition Thus the type of the result of this query is bag struct salary real partition bag struct e Employee You can work on apartition value by computing statistics on each partition The following query returns a bag of two attribute tuples with the salary and the number of employees earning each of these salaries select salary number count partition from e in Globe employees group by e salary ODMG OQL User Manual 33 2 Getting Started You get the following type of window Finally you can filter the result of grouping by applying predicates on aggregative operations You can select groups with conditions on average count sum maximum and minimum values of partitions You do this using the having clause For example if you wish to select only groups with more than one salary select salary number count partition from e in Globe employees group by e salary having count partition gt 1 The following screen is displayed EL 7 Ra 61 a 34 ODMG OQL User Manual Operators Like Order by The like operator allows you to test part of a character string The character stands for any string including the empty string The query select
33. ess street The group by operator splits the employees into partitions according to the criterion the name of the street where this person lives The select clause computes in each partition the average of the salaries of the employees belonging to this partition The result of the query is of type Bag lt struct String street float average_salary gt 3 Sort this set by salary define sorted_salary_map as select s from s in salary_map order by s average_salary ODMG OQL User Manual 55 3 OQL Rationale The result is of type List lt struct String street float average_salary gt 4 Now get the smallest salary the first in the list and take the corresponding street name This is the final result sorted_salary_map 0 street In a single query we could have written select street average_salary avg select p e salary from partition p from e in select Employee p from p in Persons where has a job in p activities group by e lives_in building address street order by avg select p e salary from partition p 0 street 56 ODMG OQL User Manual 4 OQL Reference This chapter gives the full referencial information of the object query language OQL The chapter is divided into the following sections e Introduction e Principles e Language Definition e Syntactical Abbreviations e OQL BNF The information given below is the same as that of
34. et_Employee public type unique set Employee end class o2_list_Client public type list Client end class Company public type tuple name string employees o2_set_Employee clients o2_list_Client method public title string end class Client public type tuple name string order list tuple what string price real end class Employee public type tuple name string birthday Date position string salary real method age integer end 18 ODMG OQL User Manual Basic queries In C class Company public d String name d_Set lt d_Ref lt Employee gt gt employees d List lt d_Ref lt Client gt gt clients char title return name class item d String what double price class Client public d_String name d_Array lt item gt order a class Employee public d_String name d_Date birthday d_ String position float salary int age Two persistent roots are also defined An object Globe and a collection the_employees name Globe Company constant name the_employees o2 _set_Employee ODMG OQL User Manual 19 2 Getting Started Database entry points To query any database you need various entry points In Oo these are the named objects and named values For example Globe is an entry point The simplest OQL query calls an entry point This returns if The International Globe
35. for all x in ea e relation x Example 10 lt some 8 15 7 22 is true ODMG OQL User Manual OQL BNF String Literal Os note In Oo Composite Predicate abbreviations are not supported 4 4 4 String Literal OQL accepts simple quotes as well to delimit a string see Section 4 3 3 1 as SQL does This introduces an ambiguity for a string with one character which then has the same syntax as a character literal This ambiguity is solved by context Oo note In Oo a string must be delimited by double quotes 4 5 OQL BNF The OQL grammar is given using a BNF like notation e symbol means a sequence of 0 or more symbol s e symbol means an optional symbol Do not confuse with the separators e keyword is a terminal of the grammar Keywords are not case sensitive e XXX name has the syntax of an identifier e xxx_literal is self explanatory e g a string is a string literal e bind_argument stands for a parameter when embedded in a programming language e g 3i The non terminal query stands for a valid query expression The grammar is presented as recursive rules producing valid queries This explains why most of the time this non terminal appears on the left side of Of course all operators expect their query operands to be of the right type Type constraints were discussed in the previous sections These rules must be completed by thepriority of OQL operators which is given
36. guage allowing database queries from both technical and non technical users Interactive features include fast and simple browsing of the database Browser Interface The browser interface you see depends on the operating system you are USING Unix In Unix the OoLook graphical user interface generator is used to generate the graphical form of OQL query results Figure 1 2 shows a typical query result in graphical form as generated by OoLook 1 The Object Database Standard ODMG 93 Atwood Barry Duhl Eastman Ferran Jordan Loomis and Wade Edited by R G G Cattell 1996 Morgan Kaufman Publish ers ODMG OQL User Manual System Overview Browser Interface Eraser button E l BG2S6A Set collar 100mm E7r A1l34 Fixing element WE E77 C3467 Fixing element BOS BFSF Holt J kunyas lt Boit gt l S123B6FGH fnehoring support VO8 876 Serem _ KUNYI35HGF Screw q RoS 788 A Washer KUNY S65 Washer Object icons si B CLos 2254 lt Clip KUNY 1348 lt Clip gt SSLFHIS Fixing strap P365 Anchoring clip WOr DD4 Screws BUNY1S5 35 Screw B 77990 ctoint gt KUNY23456 Joint ROS 253 Washer gt BUNY235 F Washer gt dE BA124 440BF Assembled unit SADHAF Fixing set Figure 1 2 Typical OQL query result in graphical form as generated in Unix In addition to the usual Motif buttons a graphical query result has an Eraser button Clicking on the Eraser
37. hapter contains the ODMG reference manual for OQL 1 2 It isthe same as the ODMG standard with added notes and explanations on how to use OQL with Oo For each feature of the language you get the syntax in informal semantics and an example Finally the formal syntax is given ODMG OQL User Manual Getting Started AN OBJECT ORIENTED DATABASE QUERY LANGUAGE So that you can obtain the exact information you want from your database Oo has an object oriented database query language OQL OQL is a powerful and easy to use SQL like query language with special features for dealing with complex objects values and methods This chapter introduces the OQL language and is divided up into the following sections e Basic queries e Select from where e Constructing results e Operators e Set operators e Conversions e Combining operators e Indexes e Chapter Summary To understand this chapter you need to know the ODMG data model As an introduction to the data model you can refer to chapter 3 of this manual or the O2C Beginner s Guide Experience of SQL though not a prerequisite will facilitate the OQL learning process 1 The Object Database Standard ODMG 93 release 1 2 Edited by R G G Cattell 1996 Morgan Kaufman Publishers ODMG OQL User Manual 17 Getting Started 2 1 Basic queries All the examples shown below are based on the following Op schema In O2C class o2_s
38. inition expressions is non recursive although a query may call an operation which issues a query recursively For example define jones as select distinct x from Students x where x name Jones select distinct student_id from jones This defines the set jones of students named Jones and evaluates the set of their student_ids Oo note With the O2 query interpreter you use CTRL D on Unix or CTRL Z On Windows between two queries rather that 4 3 2 Named Query Definition If ais an identifier and e is a query expression then define q as eis a query definition expression which defines the query with name q Example define Does as select x from Student x where x name Doe ODMG OQL User Manual 59 This statement defines Does as a query returning a bag containing all the students whose name is Doe define Doe as element select x from Student x where x name Doe This statement defines Doe as a query which returns the student whose name is Doe if there is only one otherwise an exception is raised Os note 4 3 3 4 3 3 1 4 3 3 2 e define operation is available only with the interactive query interpreter It has no meaning for OQL embedded in programming languages C Smalltalk OoC because standard programming language variables can be used for that purpose e A defined name is valid up to the next commit or abort e You can get the list of current defined queries by
39. ip If the method has parameters these are given between parenthesis This flexible syntax frees the user from Knowing whether the property is 52 ODMG OQL User Manual OQL by example Polymorphism stored an attribute or computed a method For instance to get the age of the oldest child of Paul we write the following query select max select c age from c in p children from p in Persons where p name Paul Of course a method can return a complex object or a collection and then its call can be embedded in a complex path expression For instance inside a building b to know who inhabits those least expensive apartment we use the following path expression b less_expensive is_used_by name Although less_expensive is a method we traverse it as if it were a relationship Polymorphism A major contribution of object technology is the possibility of manipulating polymorphic collections and thanks to the late binding mechanism to carry out generic actions on the elements of these collections For instance the set Persons contains objects of class Person Employee and Student So far all the queries against the Persons extent dealt with the three possible classes of objects of the collection A query is an expression whose operators operate on typed operands It is correct if the type of operands matches those required by the operators In this sense OQL is a typed query language This isa
40. ject while pl p2 is true if the objects have the same values even if they are not the same objects 4 3 7 Collections Expressions 4 3 7 1 Universal Quantification If xis a variable name e and e are expressions e denotes a collection and e a predicate then for all x in e 62 is an expression It returns true if all the elements of collection e satisfy e and false otherwise Example for all x in Students x student id gt 0 This returns true if all the objects in the Students set have a positive value for their student _id attribute Otherwise it returns false 68 ODMG OQL User Manual Language Definition Collections Expressions 4 3 7 2 Existential Quantification If xis a variable name if e and e are expressions e denotes a collection and e a predicate then exists x in e is an expression It returns true if there is at least one element of collection e that satisfies e and false otherwise Example This returns true if at least one course Doe takes is taught by someone named Turing If e is a collection expression then exists e and unique e are expressions which return a boolean value The first one returns true if there exists at least one element in the collection while the second one returns true if there exists only one element in the collection Notice that these operators allow the acceptance of the SQL syntax for nested queries such as select f
41. mitted Moreover the variable itself can be omitted and in this case the name of the collection itself serves as a variable name to range over it Example select couple student Students name professor z name from Students Students takes y y taught_by z where z rank full professor Oo note 4 3 8 3 4 3 9 In Oo an additional syntax is allowed to declare a variable x from x in collection This syntax will also be included in the next release of the ODMG standard Predicate In a select from where query the where clause can be omitted with the meaning of a true predicate Group by Operator If select_query is a select from where query partition_attributes is a structure expression and predicate a boolean expression then select_query group by partition_attributes is an expression and select_query group by partition_attributes having predicate is an expression The cartesian product visited by the select operator is split into partitions For each element of the cartesian product the partition attributes are evaluated All elements which match the same values according to the given partition attributes belong to the same partition Thus the partitioned set after the grouping operation is a set of structures each structure has the valued properties for this partition the valued partition_attributes completed by a property which is 72 ODMG OQL User Manual Language Definiti
42. more than two orders by how much they have paid to the company paa HE1 100000 2 Haddock pa p24 00000 i 2 8 Indexes When OQL extracts one or more elements from a collection using a specified predicate or order operation it must scan the whole collection to find the required elements You can improve performance if the system is able to directly access the matching elements This is done by establishing an index ona collection An index maps a key to one or more elements of a named collection Whenever a program searches for elements of the collection using the key the system uses the index to quicken the search This entire process is totally transparent to you as the programmer The absence or presence of an index has no effect on program code only on system performance ODMG OQL User Manual 39 2 Getting Started The benefits of indexes include the following e Complete logical and physical independence You do not have to change your query to use indexing Indexes are created by administration commands e High performance during use and maintenance Access from an index means constant time access irregardless of the size of the collection Example e Defining an index for all employees create index the_employees on salary e The following query will then be optimized select e from e in the_employees where e salary 2 1000 and e salary lt 5000 Display index The displ
43. n ee 27 RUE e ais EEEE 29 Er OEO i 30 R PEPENE E EEN AEE NAE A E fe E ETT 30 b cit 1 OEI PET IFE ATIE E TEATE A TE TT ETAETA 30 A sii ils IEI I OA ETE EE E Teer EEE E 31 ISK r PEENE N NE A E NEE AEA A AE N EEE E N ET 31 OS r E EAA ES IE ET 35 LOTO T 35 2o aron TO aaa aH ERa Eas 36 Pam ome 01 6 5 See oe pe tere tar pr itches rene ee rie eres ar eee eae 37 4 E OOIT E I ET TET EAEE AOA A TERTA 37 Pe WBE EE 37 ODMG OQL User Manual TABLE OF CONTENTS aE 1 EELA ENNE E ENT DAEA EREI E E ete eee 38 2 7 Combining operators sss ssssssssss sss ss sees sese sese 38 5 RL lt n ee ee en rn en eee ee 39 DO TE aE EA A nnn 40 2 9 Chapter Summary Beene cere ses sss ene pen ent ene areas enesenn eonenna 41 OQL Rationale 43 lt 1 The ODMG standard eee 44 eB Ty I acces 44 lt P GUL DY oram T 49 N ES eT 49 E a E rceceesisveeneepieeestis eset 31 Ieo TO anana aiaa Taa Haan KR SXT EST e E 53 Upor or compos rn an 54 OQL Reference 57 Sl ees e eastcctse erect etree mene eee sercsnceneneecnceeseces 58 da vlore D ees eee eee ee ese here en eeee eee sear enee 58 4 3 Language Definition ssssssssssssssssssssssss cesses ess esss seene ennenen 59 4 4 Syntactical Abbreviations cccccccessseseesesseseeseeeeeeeseeeennees 82 1S DUL ENP T 85 INDEX 91 ODMG OQL User Manual TABLE OF CONTENTS ODMG OQL User Manual Introduction Congratulations You are now a user
44. n expression of type character whose value is the i 1th character of the string If sis an expression of type string and low and up are expressions of type integer then s low up is an expression of type string whose value is the substring of s from the low 1 th character up to the up 1 th character If sis an expression of type string and pattern a string literal which may include the wildcard characters or _ meaning any character and or meaning any substring including an empty substring then s like pattern is an expression of type boolean whose value is true if s matches the pattern else false Example a nice string like nice tstr_ng is true ODMG OQL User Manual 65 Os note 4 3 6 4 3 6 1 4 3 6 2 4 3 6 3 wee In O2 the only supported wildcard is Object Expressions Comparison of Mutable Objects If eu and e are expressions which denote mutable objects objects with identity of the same type then Bu eo and e e are expressions which return a boolean The second expression is equivalent to not e ep eu e is true if they designate the same object Example Doe element select s from Students s where s name Doe is true Comparison of Immutable Objects If e and e are expressions which denote immutable objects literals of the same type then ei evz and ei l evp are expressions which return a boolean the
45. ng in a property whose name is then chosen as the identifier Example select p name salary student_id from Professors p p teaches This query returns a bag of structures bag lt struct name string salary float student_id integer gt Oo note Oo accepts the 3 alternatives of the projection syntax in the select part as well as the struct syntax In the group by part O2 accepts the 3 alternatives but does not accept the struct syntax ODMG OQL User Manual 83 4 4 2 Aggregate Operators These operators were introduced in Section 4 3 7 4 SQL adopts a notation which is not functionnal for them So OQL accepts this syntax too If we define aggregate as one of min max count sum and avg select count from is equivalent to count select from select aggregate query from is equivalent to aggregate select query from select aggregate distinct query from is equivalent to aggregate distinct select query from Oo note Oo does not support Aggregate Operator abbreviations 4 4 3 Composite Predicates If e and e are expressions e is a collection e has the type of its elements if relation is a relational operator l lt lt gt gt then e relationsomee and relation any e and e relation all e are expressions whose value is a boolean The two first predicates are equivalent to exists x in e e relation x The last predicate is equivalent to
46. nual 89 90 ODMG OQL User Manual INDEX ODMG OQL User Manual 91 INDEX Symbols A Accessor 87 Addition of sets 36 Aggregative operators 54 Architecture O gt 10 Arithmetic 86 Array 21 22 25 Constructing 63 Set conversion 37 array 27 29 51 Array value 21 Atomic value 20 Attribute 66 avg 30 54 70 B Bag 22 29 Constructing 63 bag 27 29 51 Boolean 87 Browser Interface 12 Unix 12 Windows NT 13 by 35 C C 11 C Interface 11 C binding 44 45 Class indicator 54 Collection 22 44 49 79 indexed expression 75 Named 39 Collection expression 87 Combining operators 28 38 Comparison 86 concatenation 76 Construction Array 51 Bag 51 List 51 Set 51 Struct 51 Constructor 27 51 87 Conversion 37 78 88 count 30 54 70 Creating objects 29 D Data manipulation 51 Database entry point 20 define 30 36 54 difference 77 distinct 23 49 92 ODMG OQL User Manual INDEX E element 31 78 except 36 54 77 Existential quantification 38 54 69 exists 31 54 F first 76 flatten 38 Flattening 79 forall in 54 from 50 G group by 32 54 55 72 H Hypertext links 13 intersect 36 54 77 intersection 77 Java 11 Java binding 44 Join 50 Join query 24 last 76 Late binding 53 like 35 List 21 22 25 Constructing 62 Set conversion 37 Values 21 list 27 51 78 listtoset 37 M max 30 54 70 Membershi
47. om e any attributes e g salary and get a set of real numbers For example select distinct e salary from e in Globe employees where e position Reporter This gives a set of the salaries of the Reporters I 240 000000 60 000000 ODMG OQL User Manual 23 2 Getting Started Join You can also use a query to select from more than one collection select e from e in Globe employees c in Globe clients where e name c name This query returns the set of employees who have the same nameasa client If there is a client called Kent and an employee called Kent you see the following window Path expressions Objects are related to other objects and in order to get to the data it needs a query can follow various paths that start from any Oo object or collection For example select distinct ord what from cl in Globe clients ord in cl order where cl name Haddock You obtain the set of what the client s called Haddock bought Book let 24 ODMG OQL User Manual Select from where Testing on nil Testing on nil After your application has updated the database you may find that some objects are now equal to nil You can test for this using OQL For example you can test that a client exists and if so which client has three orders select c name from c in Globe clients where c nil and count c order 3 To simplify programming OQL skips
48. on Group by Operator conventionally called partition and which is the bag of all objects matching this particular valued partition If the partition attributes are att e atts e2 atto e then the result of the grouping is of type set lt struct att type_of e att type of e att type_of e partition bag lt type_of grouped elements gt The type of grouped elements is defined as follows If the from clause declares the variables v on collection col v3 on col v ONcol the grouped elements form a structure with one attribute v for each collection having the type of the elements of the corresponding collection partition bag lt struct v type _of col elements Vn type_of col elements gt If a collection col has no variable declared the corresponding attribute has an internal system name This partitioned set may then be filtered by the predicate of a having clause Finally theresult is computed by evaluating the se ect clause for this partitioned and filtered set The having clause can thus apply aggregate functions on partition likewise the select clause can refer to partition to compute the final result Both clauses can refer also to the partition attributes Example select from Employees e group by low e salary lt 1000 medium e salary gt 1000 and salary lt 10000 high e salary gt 10000 This gives a set of three elements
49. p 69 ODMG OQL User Manual 93 INDEX Method call 22 52 Method invoking 52 min 30 54 70 Motif 13 N name 31 Named Collection 39 Objects 20 Query 30 Values 20 O O2 Architecture 10 OoC 11 O Corba 11 O2DBAccess 11 OoEngine 10 OosGraph 11 Ookit 11 OoLook 11 12 O ODBC 11 OoStore 10 OsTools 11 OoWeb 11 Object Creation 29 Named 20 Objects 61 ODMG model 44 ODMG standard 44 57 Operation 67 Operator 30 54 36 36 36 Aggregative 54 avg 30 54 70 Combining 28 38 Composition 54 count 30 54 70 define 30 54 element 31 except 36 54 exists 31 54 flatten 38 forall in 54 group by 32 54 55 72 intersect 36 54 like 35 max 30 54 70 min 30 54 70 order by 35 74 Set 36 38 54 sum 30 54 70 union 36 54 Wild card 38 OQL 11 12 17 Operators 30 Rational 43 Result 27 order by 35 54 74 D partition 33 Path expressions 24 49 Polymorphism 53 Predicate 50 94 ODMG OQL User Manual INDEX Q Query Basic 18 86 Named 30 Result 27 30 R Ref 44 Relationship 44 49 66 S select 55 Select from where 70 select from where 22 49 Set 22 22 Constructing 62 List conversion 37 Operators 36 54 set 27 29 51 77 78 Set expression 88 struct 27 29 29 51 Struct value 21 structure 62 Subcollection 75 75 sum 30 54 70 System Architecture 10 Testing on nil 25 Typing 80 U union 36 54 77 Universal quantification 38 54 68 Uni
50. plicit as in the second from clause you use the name of the collection directly Persons age However when there is no ambiguity you can use the property name directly as a shortcut without using the variable name to open the scope this is madeimplicitly writing simply age Thereis no ambiguity when a property name is defined for one and only one object denoted by a visible variable To summarize a name appearing in a nested query is looked up in the following order e avariable in the current scope or e a named query introduced by the define clause or e a named object i e an entry point in the database or e an attribute name or an operation name of a variable in the current scope when there is no ambiguity i e this property name belongs to only one variable in the scope Example Assuming that in the current schema the names Persons and Cities are defined select scopel from Persons Cities c where exists select scope2 from children as child or count select scope3 select scope4 from partition from children p scopes v group by age scope6 In scope1 we see the names Persons c Cities all property names of class Person and class City as soon as they are not present in both classes and they are not called Persons c nor Cities ODMG OQL User Manual 8 1 In scope2 we see the names child Persons c Cities the property names of the class City which are not property
51. r lt Boolean Expression see Section 4 3 5 query not query query query and query query query Or query Constructor see Section 4 3 4 query type name query query type name identifier query identifier query query struct identifier query identifier query query set query query j query bag query query query list query query query query query query query list query query query array query query Accessor see Sections 4 3 6 4 3 11 4 3 14 4 3 15 query query dot attribute_name query query dot relationship name query query dot operation_name query query dot operation_name query query dot f 2 query query query query query query query query query query first query query last query query function_name query query Collection Expression see Sections 4 3 7 4 4 3 query forall identifierin query query query existS identifier IN query query query existS query query unique query query query N query query query comparison_operator quantifier query quantifier some quantifier any quantifier all query count query ODMG OQL User Manual 87 4 5 1 9 4 5 1 10 4 5 1 11 4 5 2 query count query sum query query min query query max query query avg query
52. r array to a set you use the listtoset operator Example listtoset Globe clients intersect listtoset TheCompanies 2 clients Set to list To convert a set or bag to a list you must order it ODMG OQL User Manual 37 2 Getting Started For example select e from e in the_employees order by e salary returns a list sorted by salary Wake wT You can also use to build alist This avoids areal sort algorithm and should be used when the final order of the list is unimportant select e from e in the_employees order by returns a list of all employees in random order Flatten To convert a collection of collections into a flattened collection you use the flatten operator For example flatten select distinct c clients from c in TheCompanies returns a set of clients 2 7 Combining operators OQL is a complete functional language in that every operator can be combined with any other operator You can use combine and build up operators universal and existential quantifiers wild card operators standard set operators as well as list concatenation ordering and grouping operators on sets bags and lists 38 ODMG OQL User Manual Indexes Flatten For example select cl name paid sum select p price from p in cl order from cl in Globe clients where count cl order gt 2 order by sum select p price from p in cl order This sorts all the clients with
53. reall set and bag expressions then the result is obtained as follows take the cartesian product of the sets eu Go y filter that product by expression e i e eliminate from the result all objects that do not satisfy boolean expression e apply the projection to each one of the elements of this filtered set and get the result When the result is a set distinct case duplicates are automatically eliminated The situation where one or more of the collections eu e gt e S an indexed collection is a little more complex The select operator first converts all these collections into sets and applies the previous operation The result is a set distinct case or else a bag So in this case we simply transform each of the e s into a set and apply the previous definition Projection Before the projection the result of the iteration over the from variables is of type 1 Thecartesian product between a set and a bag is defined by first converting the set into a bag and then getting the resulting bag which is the cartesian product of the two bags 70 ODMG OQL User Manual Language Definition Select From Where 4 3 8 2 bag lt struct x type_of e elements Xp type_of e elements gt The projection is constructed by an expression which can then refer implicitly to the current element of this bag using the variables x If for e neither explicit nor implicit variable is declared then
54. returned by the function or the object nil when the function does not return any value The first form allows you to call a function without a parameter while the second one calls a function with the parameters eu e gt ep OQL does not define in which language the body of such a function is written This feature allows you to smoothly extend the functionality of OQL without changing the language Scope Rules The from part of a select from where query introduces explicit or implicit variables to range over the filtered collections An example of an explicit variable is select from Persons p while an implicit declaration would be select from Persons The scope of these variables reaches all parts of the select from where expression including nested sub expressions 80 ODMG OQL User Manual Language Definition Scope Rules The group by part of a select from where group_by query introduces the name partition along with possible explicit attribute names which characterize the partition These names are visible in the corresponding having and select parts including nested sub expressions within these parts Inside a scope you use these variable names to construct path expressions and reach properties attributes and operations when these variables denote complex objects For instance in the scope of the first from clause above you access the age of a person by p ade When the variable is im
55. rom col where exists select from col where predicate The nested query returns a bag to which the operator exists is applied This ts of course the task of an optimizer to recognize that it is useless to compute effectively the intermediate bag result Oo note In Oo these two last operations are not supported Only the form exists xX in e1 e2 is valid 4 3 7 3 Membership Testing Ife and e are expressions e is a collection e has the type of its elements then e ine is an expression It returns true if element e belongs to collection e3 Example Doe in Does This returns true ODMG OQL User Manual 69 4 3 7 4 4 3 8 4 3 8 1 Aggregate Operators If e is an expression which denotes a collection if lt op gt is an operator from min max count sum avg then lt op gt e iS an expression Example max select salary from Professors This returns the maximum salary of the Professors Select From Where If eu e gt Bu are expressions which denote collections and x xo X are variable names if e is an expression of type boolean and if projection is an expression or the character then select projection from eu as x4 e aS X ea as x where e and select distinct projection from eu as x1 e aS X e as x where e are expressions The result of the query is a set for a select distinct or a bag for a select If you assumee e gt e a
56. second expression is equivalent to not Leu e2 eu e S true if the value e is equal to the value ep Extracting an Attribute or Traversing a Relationship from an Object If eis an expression if pis a property name then e gt p and e p are expressions These are alternate syntax to extract the property p of an object e If e happens to designate a deleted or a non existing object i e nil an attempt to access the attribute or to traverse the relationship raises an exception However a query may test explicitly if an object is different from nil before accessing a property 66 ODMG OQL User Manual Language Definition Object Expressions Example Doe name This returns Doe Example Doe gt spouse nil and Doe gt spouse gt name Carol This returns true if Doe has a spouse whose name is Carol or else false Oo note According to a recent evolution of the ODMG standard OQL does not now raise an exception when it traverses a path which contains a nil Instead of this a predicate involving such a path is always false This means that OQL now skips such elements and thus the explicit test to nil is not yet mandatory 4 3 6 4 Applying an Operation to an Object If eis an expression if f is an operation name then e gt f and e f are expressions These are alternate syntax to apply on operation on an object The value of the expression is the one returned by the operation or else the obje
57. select p from Persons p order by p age p name This sorts the set of persons on their age then on their name and puts the sorted objects into the result as a list Each sort expression criterion can be followed by the keyword asc or desc specifying respectively an ascending or descending order The default order is that of the previous declaration For the first expression the default is ascending 74 ODMG OQL User Manual Language Definition Indexed Collection Example select from p in Persons order by p age desc p name asc p department 4 3 11 Indexed Collection Expressions 4 3 11 1 Getting the i th Element of an Indexed Collection Ife and e are expressions e is alist or an array eis an integer then e e2 is an expression This extracts the e2 1 th element of the indexed collection e4 Notice that the first element has the rank 0 Example list a b c d 1 This returns b Example element select x from Courses x where x name math and x number 101 requires 2 This returns the third prerequisite of Math 101 4 3 11 2 Extracting a Subcollection of an Indexed Collection If eu e2 and e are expressions e is alist or an array e and e are integers then e e e3 is an expression This extracts the subcollection of e starting at position e and ending at position e Example list a b c d 1 3 This returns list b c d ODMG OQL User
58. sion listtoset e is an expression This converts the list into a set by forming the set containing all the elements of the list Example listtoset list 1 2 3 2 This returns the set containing 1 2 and 3 Oo note To carry out the reverse operation set to list you use the order by operator If you are not interested in a given order you can use shown in the following query as select e from e in aSet order by 78 ODMG OQL User Manual Language Definition Conversion Expressions 4 3 13 3 4 3 13 4 Removing Duplicates Ife is an expression whose value is a collection then distinct e is an expression whose value is the same collection after removing the duplicated elements If eis a bag distinct e is aset If eis an ordered collection the relative ordering of the remaining elements is preserved Flattening Collection of Collections If eis acollection valued expression flatten e is an expression This converts a collection of collections of t into a collection of t So this flattening operates at the first level only Assuming the type of e to be col lt col lt t gt gt the result of flatten e Is e If col is a set resp a bag the union of all col lt t gt is done and the result iS a set lt t gt resp bag lt t gt e If col is a list resp an array and col is alist resp an array as well the concatenation of all col lt t gt is done following the order in
59. stance n Example set 1 2 3 This returns a set consisting of the three elements 1 2 and 3 Constructing Lists If eu ea Bu are expressions then list e ear e or simply ei amp cacy are expressions They define the list having elements eu e2 en They create a list instance If min max are two expressions of integer or character types such that min lt max then 62 ODMG OQL User Manual Language Definition Construction Expressions list min max or simply min max are expressions whose value is list min min 1 max 1 max Example list 1 2 2 3 This returns a list of four elements Example list 3 5 This returns the list 3 4 5 Oo note In Oo the keyword list is mandatory 4 3 4 5 Constructing Bags IT eu eac e pare expressions then bag e e5 e expression It defines the bag having elements eu e5 e creates a bag instance Example bag 1 1 2 3 3 This returns a bag of five elements 4 3 4 6 Constructing Arrays IT eu ear e are expressions then array Leu e e IS an expression It defines an array having elements e e2 ep It creates an array instance n Example array 3 4 2 1 1 This returns an array of five elements ODMG OQL User Manual 6 G 4 3 5 Atomic Types Expressions 4 3 5 1 Unary Expressions If eis an expression and lt op gt is a unary opera
60. t live in the same apartment as their parents the query is select c lives_in building address from p in Persons c in p children where p lives_in building address street Main Street and count p children gt 2 and c lives_in p lives_in Join In the from clause collections which are not directly related can also be declared As in SQL this allows us to compute joins between these collections For instance to find the people living in a street and having the same name as this street we do the following the Building extent is not defined in the schema so we have to compute it from the Apartments extent To compute this intermediate result we need a select from operator again So the join is done as follows 50 ODMG OQL User Manual OQL by example Data manipulation select p from p in Persons b in select distinct a building from a in Apartments where p name b address street This query highlights the need for an optimizer In this case the inner select subquery must be computed once and not for each person Data manipulation A major difference between OQL and SQL is that an object query language must manipulate complex values OQL can therefore create any complex value as a final result or inside the query as intermediate computation To build a complex value OQL uses the constructors struct set bag list and array For example to obtain the addresses of
61. tion valid for the type of e then lt op gt eis an expression It defines the result of applying lt op gt to e Arithmetic unary operators are abs Boolean unary operator is not Example This returns false 4 3 5 2 Binary Expressions Ife and e are expressions and lt op gt is a binary operation then lt op gt e is an expression It defines the result of applying lt op gt to e and evz Arithmetic integer binary operators are mod modulo Floating point binary operators are Relational binary operators are JS lt Se These operators are defined on all atomic types Boolean binary operators are and or Example count Students count TA This returns the difference between the number of students and the number of TAs 4 3 5 3 String Expressions If s and s are expressions of type string then Si So and Si So are equivalent expressions of type string whose value is the concatenation of the two strings 64 ODMG OQL User Manual Language Definition Atomic Types Expressions Os note In Oo the operator is not accepted To concatenate 2 strings use If cis an expression of type character and s an expression of type string then c ins is an expression of type boolean whose value is true if the character belongs to the string else false If sis an expression of type string and i is an expression of type integer then s i is a
62. tions The object database engine provides direct control of schemas classes objects and transactions through OoEngine API It provides full text indexing and search capabilities with OoSearch and spatial indexing and retrieval capabilities with OoSpatial It includes a Notification manager for informing other clients connected to the same Oo server that an event has occurred a Version manager for handling multiple object versions and a Replication API for synchronizing multiple copies of an O2 system 10 ODMG OQL User Manual System Overview Programming Lanquages Oo objects may be created and managed using the following programming languages utilizing all the features available with Oo persistence collection management transaction management OQL queries etc e C e C e Java e OoC s OQL Oo functions can be invoked by C programs ODMG compliant C binding ODMG compliant Java binding A powerful and elegant object oriented fourth generation language specialized for easy development of object database applications ODMG standard easy to use SQL like object query language with special features for dealing with complex Oo objects and methods Qo Development Tools e OoGraph e OoLook e Ookit e OoTools Create modify and edit any type of object graph Design and develop graphical user interfaces provides interactive manipulation of complex and multimedia objects Library of pr
63. tions each time SQL introduces a syntax which cannot enter in the category of true operators This section gives the list of these constructions that we call abbreviations since they are completely equivalent to a functional OQL expression which is also given Doing that we thus give at the same time the semantics of these constructions since all operators used for this description have already been defined 82 ODMG OQL User Manual Syntactical Abbreviations Structure Construction 4 4 1 Structure Construction The structure constructor was introduced in Section 4 3 4 2 Alternate syntax are allowed in two contexts select clause and group by clause In both contexts the SQL syntax is accepted along with the one already defined select projection projection select group by projection projection where projection is in one of the following forms e i expression as identifier e ii identifier expression e iii expression This is an alternate syntax for struct identifier expression identifier expression Ifthereis only one projection and the syntax iii is used in a select clause then it is not interpreted as a structure construction but rather the expression stands as it is Furthermore a iii expression is only valid if it is possible to infer the name of the corresponding attribute the identifier This requires that the expression denotes a path expression possibly of length one endi
64. typing the query display queries Elementary Expressions Atomic Literals If lis an atomic literal then lis an expression whose value is the literal itself Literals have the usual syntax e Object Literal nil e Boolean Literal false true e Integer Literal sequence of digits e g 27 e Float Literal mantissa exponent The exponent is optional e g 3 14 or 314 16e 2 e Character Literal character between simple quotes e g Z e String Literal character string between double quote e g a string Named Objects If eis anamed object then eis an expression It defines the entity attached to the name 60 ODMG OQL User Manual Language Definition Construction Expressions Example Students This query defines the set of students We have assumed here that the name Students exists which corresponds to the extent of objects of the class Student 4 3 3 3 Iterator Variable If xis a variable declared in a from part of a select from where then x is an expression whose value is the current element of the iteration over the corresponding collection 4 3 3 4 Named Query If define q as eis a query definition expression then qis an expression Example This query returns the student with name Doe It refers to the query definition expression declared in Section 4 3 2 4 3 4 Construction Expressions 4 3 4 1 Constructing Objects lft is atype name pi po P are properties of t
65. use A spouse is also an object of the Person class and thus appears in as a hypertext link Left clicking displays the spouse object Note The rest of this manual will only show graphical displays from the Unix platform 1 2 Interactive and embedded query language It is because OQL is so easy to use interactively that all kinds of users including non technical users can browse the database quickly and efficiently to get the information they want OQL can also be used as a function called from C C Java O2C and Oo Engine API ODMG OQL User Manual Interactive and embedded query language Interactive OQL The OQL interpreter can be triggered by the query command of O2dba O2dsa or Oo shells The command interpreter prompts you with the following message type your command and end with D To run OQL type query D You must type D Control D on a separate line You now see Query Interpreter type your query and end with D Type your query ending it with D this is a query D The answer is automatically displayed and the system returns to the OQL prompt type your query and end with D To leave the query session type D or quit You are now back in the command interpreter and you see the message type your command and end with D You can also use OQL in the OsTools programming environment Refer to the OoTools User Manual Note In a Windows environment z Control Z is us
66. x is given an internal system name which is not accessible by the query anyway By convention if the projection is simply then the result of the selection is the same as the result of the iteration If the projection is distinct the result of the select is this bag converted into a Set In all other cases the projection is explicitly computed by the given expression Example select couple student x name professor z name from Students as x x takes as y y taught_by as z where z rank full professor This returns a bag of objects of type couple giving student names and the names of the full professors from which they take classes Example select from Students as x x takes as y y taught_by as z where z rank full professor select This returns a bag of structures giving for each student object the section object followed by the student and the full professor object teaching in this section bag lt struct x Student y Section z Professor gt lterator Variables A variable x declared in the from part ranges over the collection e and thus has the type of the elements of this collection Such a variable can be used in any other part of the query to evaluate any other expressions see the Scope Rules in Section 4 3 15 Syntactical variations are ODMG OQL User Manual 71 accepted for declaring these variables exactly as with SQL The as keyword may be o
67. x 12 V Value Array 21 Atomic 20 List 21 Named 20 Struct 21 W where 50 Windows NT 13 ODMG OQL User Manual 95
68. ype system is respected This is why the language is so simple and its manual so short This philosophy is different from SQL which is an ad hoc language whose composition rules are not orthogonal to the type system Adopting a complete orthogonality makes the language easier to learn without losing the SQL style for simple queries Among the operators offered by OQL but not yet introduced we can mention the set operators union intersect except the universal forall and existential quantifiers exists the order by and group by operators and the aggregative operators count sum min max and avg To illustrate this free composition of operators let us write a rather elaborate query We want to know the name of the street where the set of employees living on that street and have the smallest average salary compared to the sets of employees living in other streets We proceed step by step and use the define OQL instruction to evaluate temporary results ODMG OQL User Manual OQL by example Operator composition 1 Build the extent of class Employee not supported directly by the schema define Employees as select Employee p from p in Persons where has a job in p activities 2 Group the employees by street and compute the average salary in each street define salary map as select street average_salary avg select p e salary from partition p from e in Employees group by e lives_in building addr
69. ze array List lt T gt a variable size and insertable array An object refers to another object through a Ref A Ref behaves as a C pointer but with more semantics it is a persistent pointer but referential integrity can be expressed in the schema and maintained by the system This is done by declaring the relationship as symmetric Combining relationships and collections an object can relate to more than one object through arelationship Therefore 1 1 relationships 1 n relationships and n m relationships can be supported with the same guarantee of referential integrity ODMG 983 enables explicit names to be given to any object or collection From aname an application can directly retrieve the named object and ODMG OQL User Manual The ODMG model then operate on it or navigate to other objects following the relationship links Let us now present the model through a complete example We use here C syntax for our object definition language following the ODMG C ODL binding i e the way of defining an ODMG schema using the standard C language ODMG OQL User Manual 45 OQL Rationale class Person d String name d Date birthdate d Set lt d_Ref lt Person gt gt parents inverse children d List lt d_Ref lt Person gt gt children inverse parents d_Ref lt Apartment gt lives_in inverse is_used_by Methods Person i Constructor a new Person is born int adla te Returns

Download Pdf Manuals

image

Related Search

Related Contents

Hardware User`s Manual  Vogel's PUC 1080  取扱説明書 GIVI PLX174  Toro Jar Top Valve Solenoid (53803) Installation and User's Guide  PTS ELETTRICHE versione 29.04.2002  Cepillo abrilllantador  19 540-01 S1IM - Galco Industrial Electronics  nirvana-notice  gebruikershandleiding user manual manuel d'utilisation  Easywalker Duo  

Copyright © All rights reserved.
Failed to retrieve file