Chaining query builder methods
You can use a coding pattern known as method chaining to write query builder code. With method chaining, the object returned by one method becomes the object from which you call the next method in the chain. Method chaining lets you fit all of your query builder code on a single line as a single statement. The object type that a chain of methods returns is the return type of the final method in the chain. If you need to use a particular object type as an argument to a function, you must ensure that the object that the chain returns is the correct type.
The following Gosu code places each query builder API call in a separate statement. The object
type of queryPerson is Query<Person>. The object
type of tableAddress is Table<Person>. The
return value of the contains method, a
Restriction<Person> object, is not used. The object type of
result is IQueryBeanResult<Person>.
uses gw.api.database.Query
// Query builder API method calls as separate statements
var queryPerson = Query.make(Person)
var tableAddress = queryPerson.join(Person#PrimaryAddress)
tableAddress.contains(Address#AddressLine1, "Lake Ave", true)
var result = queryPerson.select()
// Fetch the data with a for loop
for (person in result) {
print (person + ", " + person.PrimaryAddress.AddressLine1)
}
The following Gosu code is functionally equivalent to the sample code above, but it uses method chaining to condense the separate statements into one. Because the code uses only the value of result, an IQueryBeanResult<Person> object, none of the intermediate return objects are necessary.
uses gw.api.database.Query
// Query builder API method calls chained as a single statement
var result = Query.make(Person).join(Person#PrimaryAddress).contains(Address#AddressLine1,
"Lake Ave", true).select()
// Fetch the data with a for loop
for (person in result) {
print (person + ", " + person.PrimaryAddress.AddressLine1)
}
When you chain methods, the objects that support the calls in the chain often do not appear explicitly in your code. In the example above, the Query.make method returns a query object, on which the chained statement calls the join method. In turn, the join method returns a table object, on which the next method calls the contain method. The contain method returns a restriction object, which has a select method that returns a result object for the built-up query. After the single-line statement completes, the query object is discarded and is no longer accessible to subsequent Gosu code.
value,
which can be a chained query builder statement that returns a result
object.