# 3. Querying

db4o supplies three querying systems, Query-By-Example (QBE) Native Queries (NQ), and the SODA API. In the previous chapter, you were briefly introduced to Query By Example(QBE).
Query-By-Example (QBE) is appropriate as a quick start for users who are still acclimating to storing and retrieving objects with db4o.
Native Queries (NQ) are the main db4o query interface, recommended for general use.
SODA is the underlying internal API. It is provided for backward compatibility and it can be useful for dynamic generation of queries, where NQ are too strongly typed.

## 3.1. Query by Example (QBE)

When using Query By Example (QBE) you provide db4o with a template object. db4o will return all of the objects which match all non-default field values. This is done via reflecting all of the fields and building a query expression where all non-default-value fields are combined with AND expressions. Here's an example from the previous chapter:

`[retrievePilotByName] Dim proto As Pilot = New Pilot("Michael Schumacher", 0) Dim result As ObjectSet = db.[Get](proto) ListResult(result)`

Querying this way has some obvious limitations:
- db4o must reflect all members of your example object.
- You cannot perform advanced query expressions. (AND, OR, NOT, etc.)
- You cannot constrain on values like 0 (integers), "" (empty strings), or nulls (reference types) because they would be interpreted as unconstrained.
- You need to be able to create objects without initialized fields. That means you can not initialize fields where they are declared. You can not enforce contracts that objects of a class are only allowed in a well-defined initialized state.
- You need a constructor to create objects without initialized fields.
To get around all of these constraints, db4o provides the Native Query (NQ) system.

## 3.2. Native Queries

Wouldn't it be nice to pose queries in the programming language that you are using? Wouldn't it be nice if all your query code was 100% typesafe, 100% compile-time checked and 100% refactorable? Wouldn't it be nice if the full power of object-orientation could be used by calling methods from within queries? Enter Native Queries.
Native queries are the main db4o query interface and they are the recommended way to query databases from your application. Because native queries simply use the semantics of your programming language, they are perfectly standardized and a safe choice for the future.
Native Queries are available for all platforms supported by db4o.

## 3.2.1. Concept

The concept of native queries is taken from the following two papers:
- Cook/Rosenberger, Native Queries for Persistent Objects, A Design White Paper
- Cook/Rai, Safe Query Objects: Statically Typed Objects as Remotely Executable Queries

## 3.2.2. Principle

Native Queries provide the ability to run one or more lines of code against all instances of a class. Native query expressions should return true to mark specific instances as part of the result set. db4o will attempt to optimize native query expressions and run them against indexes and without instantiating actual objects, where this is possible.

## 3.2.3. Simple Example

Let's look at how a simple native query will look like in some of the programming languages and dialects that db4o supports:
C# .NET 2.0

`IList <Pilot> pilots = db.Query <Pilot> (delegate(Pilot pilot) { return pilot.Points == 100; });`

Java JDK 5

`List <Pilot> pilots = db.query(new Predicate<Pilot>() { public boolean match(Pilot pilot) { return pilot.getPoints() == 100; } });`

Java JDK 1.2 to 1.4

`List pilots = db.query(new Predicate() { public boolean match(Pilot pilot) { return pilot.getPoints() == 100; } });`

Java JDK 1.1

`ObjectSet pilots = db.query(new PilotHundredPoints()); public static class PilotHundredPoints extends Predicate { public boolean match(Pilot pilot) { return pilot.getPoints() == 100; } }`

C# .NET 1.1

`IList pilots = db.Query(new PilotHundredPoints()); public class PilotHundredPoints : Predicate { public boolean Match(Pilot pilot) { return pilot.Points == 100; } }`

VB .NET 1.1

`Dim pilots As IList = db.Query(new PilotHundredPoints()) Public Class PilotHundredPoints Inherits Predicate Public Function Match (pilot As Pilot) as Boolean If pilot.Points = 100 Then Return True Else Return False End Function End Class`

A side note on the above syntax:
For all dialects without support for generics, Native Queries work by convention. A class that extends the com.db4o.Predicate class is expected to have a boolean #match() or #Match() method with one parameter to describe the class extent:

`bool Match(Pilot candidate);`

When using native queries, don't forget that modern integrated development environments (IDEs) can do all the typing work around the native query expression for you, if you use templates and autocompletion.
Here is how to configure a Native Query template with Eclipse 3.1:
From the menu, choose Window + Preferences + Java + Editor + Templates + New
As the name type "nq". Make sure that "java" is selected as the context on the right. Paste the following into the pattern field:

`List <${extent}> list = db.query(new Predicate <${extent}> () { public boolean match(${extent} candidate){ return true; } });`

Now you can create a native query with three keys: n + q + Control-Space.
Similar features are available in most modern IDEs.

## 3.2.4. Advanced Example

For complex queries, the native syntax is very precise and quick to write. Let's compare to a SODA query that finds all pilots with a given name or a score within a given range:

`[storePilots] db.[Set](New Pilot("Michael Schumacher", 100)) db.[Set](New Pilot("Rubens Barrichello", 99))`

`[retrieveComplexSODA] Dim query As Query = db.Query() query.Constrain(GetType(Pilot)) Dim pointQuery As Query = query.Descend("_points") query.Descend("_name").Constrain("Rubens Barrichello").[Or](pointQuery.Constrain(99).Greater().[And](pointQuery.Constrain(199).Smaller())) Dim result As ObjectSet = query.Execute() ListResult(result)`

OUTPUT: 2 Rubens Barrichello/99 Michael Schumacher/100

Here is how the same query will look like with native query syntax, fully accessible to autocompletion, refactoring and other IDE features, fully checked at compile time:
C# .NET 2.0

`IList <Pilot> result = db.Query<Pilot> (delegate(Pilot pilot) { return pilot.Points > 99 && pilot.Points < 199 || pilot.Name == "Rubens Barrichello"; });`

Java JDK 5

`List <Pilot> result = db.query(new Predicate<Pilot>() { public boolean match(Pilot pilot) { return pilot.getPoints() > 99 && pilot.getPoints() < 199 || pilot.getName().equals("Rubens Barrichello"); } });`

## 3.2.5. Arbitrary Code

Basically that's all there is to know about native queries to be able to use them efficiently. In principle you can run arbitrary code as native queries, you just have to be very careful with side effects - especially those that might affect persistent objects.
Let's run an example that involves some more of the language features available.

`Imports com.db4o.query
Namespace com.db4o.f1.chapter1
Public Class ArbitraryQuery
Inherits Predicate
Private _points As Integer()
Public Sub New(ByVal points As Integer())
_points = points
End Sub
Public Function Match(ByVal pilot As Pilot) As Boolean
For Each points As Integer In _points
If pilot.Points = points Then
Return True
End If
Next
Return pilot.Name.StartsWith("Rubens")
End Function
End Class
End Namespace
`

## 3.2.6. Native Query Performance

One drawback of native queries has to be pointed out: Under the hood db4o tries to analyze native queries to convert them to SODA. This is not possible for all queries. For some queries it is very difficult to analyze the flowgraph. In this case db4o will have to instantiate some of the persistent objects to actually run the native query code. db4o will try to analyze parts of native query expressions to keep object instantiation to the minimum.
The development of the native query optimization processor will be an ongoing process in a close dialog with the db4o community. Feel free to contribute your results and your needs by providing feedback to our db4o forums.
With the current implementation, all above examples will run optimized, except for the "Arbitrary Code" example - we are working on it.

## 3.2.7. Full source

`Imports com.db4o
Imports com.db4o.query
Namespace com.db4o.f1.chapter1
Public Class NQExample
Inherits Util
Public Shared Sub Main(ByVal args As String())
Dim db As ObjectContainer = Db4oFactory.OpenFile(Util.YapFileName)
Try
StorePilots(db)
RetrieveComplexSODA(db)
RetrieveComplexNQ(db)
RetrieveArbitraryCodeNQ(db)
ClearDatabase(db)
Finally
db.Close()
End Try
End Sub
Public Shared Sub StorePilots(ByVal db As ObjectContainer)
db.[Set](New Pilot("Michael Schumacher", 100))
db.[Set](New Pilot("Rubens Barrichello", 99))
End Sub
Public Shared Sub RetrieveComplexSODA(ByVal db As ObjectContainer)
Dim query As Query = db.Query()
query.Constrain(GetType(Pilot))
Dim pointQuery As Query = query.Descend("_points")
query.Descend("_name").Constrain("Rubens Barrichello").[Or](pointQuery.Constrain(99).Greater().[And](pointQuery.Constrain(199).Smaller()))
Dim result As ObjectSet = query.Execute()
ListResult(result)
End Sub
Public Shared Sub RetrieveComplexNQ(ByVal db As ObjectContainer)
Dim result As ObjectSet = db.Query(New ComplexQuery())
ListResult(result)
End Sub
Public Shared Sub RetrieveArbitraryCodeNQ(ByVal db As ObjectContainer)
Dim result As ObjectSet = db.Query(New ArbitraryQuery(New Integer() {1, 100}))
ListResult(result)
End Sub
Public Shared Sub ClearDatabase(ByVal db As ObjectContainer)
Dim result As ObjectSet = db.[Get](GetType(Pilot))
While result.HasNext()
db.Delete(result.[Next]())
End While
End Sub
End Class
End Namespace
`

`Imports com.db4o.query Namespace com.db4o.f1.chapter1 Public Class ComplexQuery Inherits Predicate Public Function Match(ByVal pilot As Pilot) As Boolean Return pilot.Points > 99 AndAlso pilot.Points < 199 OrElse pilot.Name = "Rubens Barrichello" End Function End Class End Namespace`

`Imports com.db4o.query
Namespace com.db4o.f1.chapter1
Public Class ArbitraryQuery
Inherits Predicate
Private _points As Integer()
Public Sub New(ByVal points As Integer())
_points = points
End Sub
Public Function Match(ByVal pilot As Pilot) As Boolean
For Each points As Integer In _points
If pilot.Points = points Then
Return True
End If
Next
Return pilot.Name.StartsWith("Rubens")
End Function
End Class
End Namespace
`

## 3.3. SODA Query API

The SODA query API is db4o's low level querying API, allowing direct access to nodes of query graphs. Since SODA uses strings to identify fields, it is neither perfectly typesafe nor compile-time checked and it also is quite verbose to write.
For most applications Native Queries will be the better querying interface.
However there can be applications where dynamic generation of queries is required, that's why SODA is explained here.

## 3.3.1. Simple queries

Let's see how our familiar QBE queries are expressed with SODA. A new Query object is created through the #query() method of the ObjectContainer and we can add Constraint instances to it. To find all Pilot instances, we constrain the query with the Pilot class object.

`[retrieveAllPilots] Dim query As Query = db.Query() query.Constrain(GetType(Pilot)) Dim result As ObjectSet = query.Execute() ListResult(result)`

OUTPUT: 2 Rubens Barrichello/99 Michael Schumacher/100

Basically, we are exchanging our 'real' prototype for a meta description of the objects we'd like to hunt down: a query graph made up of query nodes and constraints. A query node is a placeholder for a candidate object, a constraint decides whether to add or exclude candidates from the result.
Our first simple graph looks like this.
We're just asking any candidate object (here: any object in the database) to be of type Pilot to aggregate our result.
To retrieve a pilot by name, we have to further constrain the candidate pilots by descending to their name field and constraining this with the respective candidate String.

`[retrievePilotByName] Dim query As Query = db.Query() query.Constrain(GetType(Pilot)) query.Descend("_name").Constrain("Michael Schumacher") Dim result As ObjectSet = query.Execute() ListResult(result)`

OUTPUT: 1 Michael Schumacher/100

What does 'descend' mean here? Well, just as we did in our 'real' prototypes, we can attach constraints to child members of our candidates.
So a candidate needs to be of type Pilot and have a member named 'name' that is equal to the given String to be accepted for the result.
Note that the class constraint is not required: If we left it out, we would query for all objects that contain a 'name' member with the given value. In most cases this will not be the desired behavior, though.
Finding a pilot by exact points is analogous.

`[retrievePilotByExactPoints] Dim query As Query = db.Query() query.Constrain(GetType(Pilot)) query.Descend("_points").Constrain(100) Dim result As ObjectSet = query.Execute() ListResult(result)`

OUTPUT: 1 Michael Schumacher/100

## 3.3.2. Advanced queries

Now there are occasions when we don't want to query for exact field values, but rather for value ranges, objects not containing given member values, etc. This functionality is provided by the Constraint API.
First, let's negate a query to find all pilots who are not Michael Schumacher:

`[retrieveByNegation] Dim query As Query = db.Query() query.Constrain(GetType(Pilot)) query.Descend("_name").Constrain("Michael Schumacher").[Not]() Dim result As ObjectSet = query.Execute() ListResult(result)`

OUTPUT: 1 Rubens Barrichello/99

Where there is negation, the other boolean operators can't be too far.

`[retrieveByConjunction] Dim query As Query = db.Query() query.Constrain(GetType(Pilot)) Dim constr As Constraint = query.Descend("_name").Constrain("Michael Schumacher") query.Descend("_points").Constrain(99).[And](constr) Dim result As ObjectSet = query.Execute() ListResult(result)`

OUTPUT: 0

`[retrieveByDisjunction] Dim query As Query = db.Query() query.Constrain(GetType(Pilot)) Dim constr As Constraint = query.Descend("_name").Constrain("Michael Schumacher") query.Descend("_points").Constrain(99).[Or](constr) Dim result As ObjectSet = query.Execute() ListResult(result)`

OUTPUT: 2 Rubens Barrichello/99 Michael Schumacher/100

We can also constrain to a comparison with a given value.

`[retrieveByComparison] Dim query As Query = db.Query() query.Constrain(GetType(Pilot)) query.Descend("_points").Constrain(99).Greater() Dim result As ObjectSet = query.Execute() ListResult(result)`

OUTPUT: 1 Michael Schumacher/100

The query API also allows to query for field default values.

`[retrieveByDefaultFieldValue] Dim somebody As Pilot = New Pilot("Somebody else", 0) db.[Set](somebody) Dim query As Query = db.Query() query.Constrain(GetType(Pilot)) query.Descend("_points").Constrain(0) Dim result As ObjectSet = query.Execute() ListResult(result) db.Delete(somebody)`

OUTPUT: 1 Somebody else/0

It is also possible to have db4o sort the results.

`[retrieveSorted] Dim query As Query = db.Query() query.Constrain(GetType(Pilot)) query.Descend("_name").OrderAscending() Dim result As ObjectSet = query.Execute() ListResult(result) query.Descend("_name").OrderDescending() result = query.Execute() ListResult(result)`

OUTPUT: 2 Michael Schumacher/100 Rubens Barrichello/99 2 Rubens Barrichello/99 Michael Schumacher/100

All these techniques can be combined arbitrarily, of course. Please try it out. There still may be cases left where the predefined query API constraints may not be sufficient - don't worry, you can always let db4o run any arbitrary code that you provide in an Evaluation. Evaluations will be discussed in a later chapter.
To prepare for the next chapter, let's clear the database.

`[clearDatabase] Dim result As ObjectSet = db.[Get](GetType(Pilot)) For Each item As Object In result db.Delete(item) Next`

OUTPUT:

## 3.3.3. Conclusion

Now you have been provided with three alternative approaches to query db4o databases: Query-By-Example, Native Queries, SODA.
Which one is the best to use? Some hints:
- Native queries are targetted to be the primary interface for db4o, so they should be preferred.
- With the current state of the native query optimizer there may be queries that will execute faster in SODA style, so it can be used to tune applications. SODA can also be more convenient for constructing dynamic queries at runtime.
- Query-By-Example is nice for simple one-liners, but restricted in functionality. If you like this approach, use it as long as it suits your application's needs.
Of course you can mix these strategies as needed.
We have finished our walkthrough and seen the various ways db4o provides to pose queries. But our domain model is not complex at all, consisting of one class only. Let's have a look at the way db4o handles object associations in the next chapter .

## 3.3.4. Full source

`Imports System
Imports com.db4o
Imports com.db4o.query
Namespace com.db4o.f1.chapter1
Public Class QueryExample
Inherits Util
Public Shared Sub Main(ByVal args As String())
Dim db As ObjectContainer = Db4oFactory.OpenFile(Util.YapFileName)
Try
StoreFirstPilot(db)
StoreSecondPilot(db)
RetrieveAllPilots(db)
RetrievePilotByName(db)
RetrievePilotByExactPoints(db)
RetrieveByNegation(db)
RetrieveByConjunction(db)
RetrieveByDisjunction(db)
RetrieveByComparison(db)
RetrieveByDefaultFieldValue(db)
RetrieveSorted(db)
ClearDatabase(db)
Finally
db.Close()
End Try
End Sub
Public Shared Sub StoreFirstPilot(ByVal db As ObjectContainer)
Dim pilot1 As Pilot = New Pilot("Michael Schumacher", 100)
db.[Set](pilot1)
Console.WriteLine("Stored {0}", pilot1)
End Sub
Public Shared Sub StoreSecondPilot(ByVal db As ObjectContainer)
Dim pilot2 As Pilot = New Pilot("Rubens Barrichello", 99)
db.[Set](pilot2)
Console.WriteLine("Stored {0}", pilot2)
End Sub
Public Shared Sub RetrieveAllPilots(ByVal db As ObjectContainer)
Dim query As Query = db.Query()
query.Constrain(GetType(Pilot))
Dim result As ObjectSet = query.Execute()
ListResult(result)
End Sub
Public Shared Sub RetrievePilotByName(ByVal db As ObjectContainer)
Dim query As Query = db.Query()
query.Constrain(GetType(Pilot))
query.Descend("_name").Constrain("Michael Schumacher")
Dim result As ObjectSet = query.Execute()
ListResult(result)
End Sub
Public Shared Sub RetrievePilotByExactPoints(ByVal db As ObjectContainer)
Dim query As Query = db.Query()
query.Constrain(GetType(Pilot))
query.Descend("_points").Constrain(100)
Dim result As ObjectSet = query.Execute()
ListResult(result)
End Sub
Public Shared Sub RetrieveByNegation(ByVal db As ObjectContainer)
Dim query As Query = db.Query()
query.Constrain(GetType(Pilot))
query.Descend("_name").Constrain("Michael Schumacher").[Not]()
Dim result As ObjectSet = query.Execute()
ListResult(result)
End Sub
Public Shared Sub RetrieveByConjunction(ByVal db As ObjectContainer)
Dim query As Query = db.Query()
query.Constrain(GetType(Pilot))
Dim constr As Constraint = query.Descend("_name").Constrain("Michael Schumacher")
query.Descend("_points").Constrain(99).[And](constr)
Dim result As ObjectSet = query.Execute()
ListResult(result)
End Sub
Public Shared Sub RetrieveByDisjunction(ByVal db As ObjectContainer)
Dim query As Query = db.Query()
query.Constrain(GetType(Pilot))
Dim constr As Constraint = query.Descend("_name").Constrain("Michael Schumacher")
query.Descend("_points").Constrain(99).[Or](constr)
Dim result As ObjectSet = query.Execute()
ListResult(result)
End Sub
Public Shared Sub RetrieveByComparison(ByVal db As ObjectContainer)
Dim query As Query = db.Query()
query.Constrain(GetType(Pilot))
query.Descend("_points").Constrain(99).Greater()
Dim result As ObjectSet = query.Execute()
ListResult(result)
End Sub
Public Shared Sub RetrieveByDefaultFieldValue(ByVal db As ObjectContainer)
Dim somebody As Pilot = New Pilot("Somebody else", 0)
db.[Set](somebody)
Dim query As Query = db.Query()
query.Constrain(GetType(Pilot))
query.Descend("_points").Constrain(0)
Dim result As ObjectSet = query.Execute()
ListResult(result)
db.Delete(somebody)
End Sub
Public Shared Sub RetrieveSorted(ByVal db As ObjectContainer)
Dim query As Query = db.Query()
query.Constrain(GetType(Pilot))
query.Descend("_name").OrderAscending()
Dim result As ObjectSet = query.Execute()
ListResult(result)
query.Descend("_name").OrderDescending()
result = query.Execute()
ListResult(result)
End Sub
Public Shared Sub ClearDatabase(ByVal db As ObjectContainer)
Dim result As ObjectSet = db.[Get](GetType(Pilot))
For Each item As Object In result
db.Delete(item)
Next
End Sub
End Class
End Namespace
`

--
generated by Doctor courtesy of db4objects Inc.