0% found this document useful (0 votes)
20 views

Ariba Spend Management Query API Guide 9r2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Ariba Spend Management Query API Guide 9r2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Ariba Spend Management™

Query API Guide


Release 9r2
Document Version 1
June 2014
Copyright © 1996–2014 Ariba, Inc. All rights reserved.

This documentation, as well as the Ariba software and/or services described in it, contain proprietary information. They are provided under a license or other
agreement containing restrictions on use and disclosure and are also protected by copyright, patent and/or other intellectual property laws. Except as permitted
by such agreement, no part of the document may be reproduced or transmitted in any form by any means, electronic, mechanical or otherwise, without the
prior written permission of Ariba, Inc.

Ariba, Inc. assumes no responsibility or liability for any errors or inaccuracies that may appear in the documentation. The information contained in the
documentation is subject to change without notice.

Ariba, the Ariba logo, AribaLIVE, SupplyWatch, Ariba.com, Ariba.com Network and Ariba Spend Management. Find it. Get it. Keep it. and PO-Flip are
registered trademarks of Ariba, Inc. Ariba Procure-to-Pay, Ariba Buyer, Ariba eForms, Ariba PunchOut, Ariba Services Procurement, Ariba Travel and
Expense, Ariba Procure-to-Order, Ariba Procurement Content, Ariba Sourcing, Ariba Savings and Pipeline Tracking, Ariba Category Management, Ariba
Category Playbooks, Ariba StartSourcing, Ariba Spend Visibility, Ariba Analysis, Ariba Data Enrichment, Ariba Contract Management, Ariba Contract
Compliance, Ariba Electronic Signatures, Ariba StartContracts, Ariba Invoice Management, Ariba Payment Management, Ariba Working Capital
Management, Ariba Settlement, Ariba Supplier Information and Performance Management, Ariba Supplier Information Management, Ariba Discovery, Ariba
Invoice Automation, Ariba PO Automation, Ariba Express Content, Ariba Ready, and Ariba LIVE are trademarks or service marks of Ariba, Inc. All other
brand or product names may be trademarks or registered trademarks of their respective companies or organizations in the United States and/or other countries.

Ariba Sourcing solutions (On Demand and software) are protected by one or more of the following patents, including without limitation: U.S. Patent Nos.
6,199,050; 6,216,114; 6,223,167; 6,230,146; 6,230,147; 6,285,989; 6,408,283; 6,499,018; 6,564,192; 6,871,191; 6,952,682; 7,010,511; 7,072,061; 7,130,815;
7,146,331; 7,152,043;7,225,152; 7,277,878; 7,249,085; 7,283,979; 7,283,980; 7,296,001; 7,346,574; 7,383,206; 7,395,238; 7,401,035; 7,407,035; 7,444,299;
7,483,852; 7,499,876; 7,536,362; 7,558,746; 7,558,752; 7,571,137; 7,599,878; 7,634,439; 7,657,461; and 7,693,747. Patents pending.

Other Ariba product solutions are protected by one or more of the following patents:

U.S. Patent Nos. 6,199,050, 6,216,114, 6,223,167, 6,230,146, 6,230,147, 6,285,989, 6,408,283, 6,499,018, 6,564,192, 6,584,451, 6,606,603, 6,714,939,
6,871,191, 6,952,682, 7,010,511, 7,047,318, 7,072,061, 7,084,998; 7,117,165; 7,225,145; 7,324,936; and 7,536,362. Patents pending.

Certain Ariba products may include third party software or other intellectual property licensed from a third party. For information regarding software or other
intellectual property licensed from a third party, go to http://www.ariba.com/copyrights.cfm.
Revision History

The following table provides a brief history of the updates to this guide. Ariba updates the technical
documentation for its On-Premise solutions if
• software changes delivered in service packs or hot fixes require a documentation update to correctly
reflect the new or changed functionality;
• the existing content is incorrect or user feedback indicated that important content is missing.

Ariba reserves the right to update its technical documentation without prior notification. Most
documentation updates will be made available in the same week as the software service packs are released,
but critical documentation updates may be released at any time.

Version Month/Year of Updated Chapter/Section Short Description of Change


Update
1 June 2014 n/a GA version

Ariba Upstream Platform Configuration Guide iii


Revision History

iv Ariba Upstream Platform Configuration Guide


Table of Contents

Revision History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii

Chapter 1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Advantages of the Ariba Query API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Query Defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
SQL-Independence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Query API Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Testing and Debugging Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Using the Inspector to Run Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Using the Command Line Tool. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Setting Log Categories for the Ariba Query API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Using this Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Chapter 2
Ariba Query API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Ariba Query API Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Constructing a Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Building a String Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Building a Query with Java Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Executing Query Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Specifying Query Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Validating a Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Executing a Query. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Executing an Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Processing Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Checking Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Accessing Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Accessing Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
AQLError Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Chapter 3
Writing Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Common Defaults for Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Filtering for Active Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Filtering by Partition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Filtering for Locale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Accessing Data through Field Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Accessing Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Accessing Normalized Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Using Dot Notation in Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Metadata XML Settings Affecting Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

Ariba Spend Management Query API Guide v


Table of Contents

Query Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Auto-Join Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Vector Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
The Query Result Cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Using the Cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Using the Cache with a Nametable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Configuration Settings for the Cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

Chapter 4
Query Language Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Syntax Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Terminal Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Other Punctuation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Annotated Grammar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Select Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Class and Field References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Join Clauses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Conditional Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Scalar Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Other Statement Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Known Limitations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

Appendix A
Reserved Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

Appendix B
Command Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
aribaquery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

vi Ariba Spend Management Query API Guide


Chapter 1
Introduction

You use the Ariba Query API to query your database from Java code. Ariba Query API provides
functionality much like that of SQL and the query language follows the basic SQL SELECT ... FROM ....
syntax.

The chief advantage of the Query API over raw SQL is that it is integrated with metadata XML and thus
allows you to express queries in terms of your object model’s classes and fields.

The Query API also provides defaults that make it easier to express common idioms, such as restricting a
query to the objects in a given partition, or defining a query so that it does not return objects marked as
inactive in the database.

This document describes how to create and execute queries using the Ariba Query API. It assumes that you
are familiar with using metadata XML files to define an object model, and that you have a basic knowledge
of SQL and database queries.

Advantages of the Ariba Query API


The Ariba Query API provides a layer on top of the database that allows you to write queries at the Java
object model level, rather than the database level.

The basic query syntax is a SELECT ... FROM ... statement, with an optional WHERE clause, as in SQL. In
Ariba Query API queries, the terms in the SELECT statement are fields and classes from your object model,
rather than database tables and columns (as they would be in SQL). The following is a simple example:

SELECT EmailAddress FROM ariba.user.core.User

The Ariba Query API reads the query statement, translates the Java field names into database tables, and
generates a SQL statement. For this example, the SQL statement might be as follows:

SELECT Use1.us_EmailAddress
FROM UserTab Use1

In this example, the terms in the SELECT statement refer to the Java class names (such as
ariba.user.core.User), and not database tables names (such as UserTab). The Query API is strongly typed,
and is able to validate class and field names based on the typing information in metadata XML files.

You can also use the Ariba Query API to execute raw SQL statements.

Query Defaults
The Query API provides default parameters and settings for common query options. These defaults mean
that you can omit many standard clauses from your queries, and have them defaulted by Ariba Query API.
For example, by default, the Query API adds an INCLUDE ACTIVE clause to all queries, to select items marked

Ariba Spend Management Query API Guide 7


Query API Overview Chapter 1 Introduction

as active in the database (and exclude those marked as inactive). When you construct a query, you do not
have to explicitly include a clause to omit inactive objects. For example, consider the query used in the
previous example:

SELECT EmailAddress FROM ariba.user.core.User

When the Ariba Query API generates the SQL for this query, the default is to add a filter for active objects,
and also a filter that restricts the query by partition. The actual SQL generated for this query statement might
be as follows:

SELECT Use1.us_EmailAddress
FROM UserTab Use1
WHERE (Use1.us_Active = 1) AND
(Use1.us_PartitionNumber = 0 OR Use1.us_PartitionNumber = 2)

If the defaults are not appropriate, you can override them by supplying explicit query terms. The defaults
exist to provide convenient shortcuts for common idioms.

SQL-Independence
Another advantage of the Ariba Query API is that it insulates you from the details of the underlying SQL
implementation. SQL tends to vary in certain details between RDBMS vendors. The Ariba Query API is
RDBMS-independent, which means that you can write your queries without needing to know the details of
the underlying SQL implementation.

Query API Overview


To use the Ariba Query API, you typically construct a query, execute it, and read results, from your Java
code.

Internally, a query is a Java object, and you run that query by calling Java methods in the BaseService class.
You can construct the query either by using Java methods in the Query API or by writing the query as a
query string (using SQL-like syntax), and then parsing the string into an object. The query data is returned in
a Java object, an AQLResultCollection, which you can then process with methods in the Java API to extract
results.

Most Ariba Query API query statements are SELECT statements, but there is also limited support for UPDATE
statements and other SQL statement types.

For information on the Java API for running and parsing queries, see “Ariba Query API Overview” on
page 11.

Testing and Debugging Queries


To test queries, you can submit ad hoc queries to the database using either the Inspector or the aribaquery
command line tool.

8 Ariba Spend Management Query API Guide


Chapter 1 Introduction Testing and Debugging Queries

Using the Inspector to Run Queries


The Inspector is a diagnostic tool that allows you to examine the contents of the Ariba database. You can use
the Inspector to submit queries to the database, in query string format.

 To use the Inspector to look at the Ariba application object model:


1 Open a Web browser and connect to the following URL:
http://yourServer:HTTPServerPort/application/inspector

application is the name of the Ariba application, such as Buyer or ACM.


2 In the Inspector, type a query in the Query Statement box and click Submit Query. For example.

Using the Command Line Tool


The aribaquery command line tool interprets query strings on the command line and submits them as
database queries. To run aribaquery, change directories to your installation bin directory and type the
following at a command prompt:

aribaquery -username <xxx> -password <xxx> -host <hostname> -port <rpc port>

(If you are not using SSL, you must supply the -noSsl option as well.)

You can use aribaquery to submit arbitrary query strings. For example:

AQL> SELECT Country from ariba.basic.core.Country AS Country;

To indicate that you have entered a complete statement, you must either terminate the command with a
semicolon, or type go on a separate line after you submit the command. For example:

AQL> SELECT Country from ariba.basic.core.Country AS Country WHERE Name > 'Algeria' AND Name <
'Canada'
AQL> go

The keywords you use with aribaquery, such as go, quit, and exit, are
case-insensitive. The options, such as -username, are case-sensitive.

For a complete list of options available for aribaquery, see “aribaquery” on page 71.

Ariba Spend Management Query API Guide 9


Using this Document Chapter 1 Introduction

Setting Log Categories for the Ariba Query API


The main log categories for debugging Ariba Query API are as follows:
• query. This category enables log messages that show both the Ariba Query API statements and any SQL
statements generated from the original Ariba Query API statement
• queryperf. This category enables query performance logging that shows the number of rows returned by
the query, and the time spent parsing, validating, generating and executing.
• aql. This category enables extensive logging, including the construction of each query.

The aql category includes both query and queryperf. If you turn on aql, the query and queryperf categories
are also enabled. If you use either queryperf or aql, you should set the log level to info.

A setting of queryperf/debug logs performance information for every query, which can generate a lot of
output in the query logs. A setting of queryperf/info uses parameters from config/Parameters.table to
determine a cutoff for which queries to include. The queryperf/info category traces the following types of
queries:
• Queries that take more than System.Debug.QueryExecutionThresholdMilliseconds to execute
• Queries that generate more than System.Debug.QueryGenerationThresholdSQLBytes of SQL
• Queries that use SELECT *

For example, to debug slow queries, you could do the following:


1 Enable the log file category queryperf/info

2 Determine a threshold in milliseconds that you feel would be acceptable to your end users, and set the
System.Debug.QueryExecutionThresholdMilliseconds parameter to this value. For example:
QueryExecutionThresholdMilliseconds=7000

3 Restart your Ariba Spend Management application.

All queries that exceed the specified threshold are logged to the log file. This will identify slow running
queries and provide insight into areas that need to be tuned.

Using this Document


This document introduces the Java API and then provides details on constructing queries. It includes the
following chapters:
• Chapter 2, “Ariba Query API,” introduces the Java classes available in the Query API, and provides a
high-level overview of the Query API
• Chapter 3, “Writing Queries,” illustrates how the Ariba Query API can simplify the queries you write, and
shows examples of constructing queries
• Chapter 4, “Query Language Details,” provides a complete description of the Ariba Query API language

Additionally, the appendixes provide reference information on the reserved words and command-line tools
in the Ariba Query API.

10 Ariba Spend Management Query API Guide


Chapter 2
Ariba Query API

This chapter provides an overview of how to access the Query API from Java code. It includes the following
sections:
• “Ariba Query API Overview” on page 11
• “Constructing a Query” on page 12
• “Executing Query Statements” on page 14
• “Processing Results” on page 16

Ariba Query API Overview


The Java classes that define the Ariba Query API are in the package ariba.base.core.aql and have the
prefix AQL (Ariba Query Layer).

Typical use of Ariba Query API involves the following steps:


1 Constructing a query, either as a Java object or as a string

2 Optionally adding conditions (constraints) to the query

3 Running an operation on that query, (usually execute)

4 Processing the results

The example on the next page shows a simplified example of the API.

public static List lookupAddresses (Partition partition,


AQLCondition condition,
int rowLimit)
{
// Create the query for this class
AQLQuery query = new AQLQuery(ClassName, true);

// Add a condition (see below)


query.and(condition);

// Run the query


AQLOptions options = new AQLOptions(partition, false);
options.setRowLimit(rowLimit);
AQLResultCollection results =
Base.getService().executeQuery(query, options);

// Process the results


List addresses = ListUtil.list();
while (results.next()) {
BaseId id = results.getBaseId(0);
addresses.add(Base.getSession().objectFromId(id));
}

return addresses;
}

Ariba Spend Management Query API Guide 11


Constructing a Query Chapter 2 Ariba Query API

// Create the AQL condition, expressing query constraints


public static AQLCondition buildCondition (String street,
String city)
{
AQLClassReference typeRef = new AQLClassReference(ClassName);

List conditions = ListUtil.list();

if (!StringUtil.nullOrEmptyOrBlankString(street)) {
conditions.add(
AQLCondition.buildEqual(
typeRef.buildField(Address.KeyLines), street));
}

if (!StringUtil.nullOrEmptyOrBlankString(city)) {
conditions.add(
AQLCondition.buildEqual(
typeRef.buildField(Address.KeyCity), city));
}
return AQLCondition.buildAnd(conditions);
}

The rest of this chapter describes each of these steps in more detail.

Constructing a Query
In the Ariba Query API, you can create a query either as a string query or a query object:
• A string query is a SQL-like string, such as SELECT Name FROM Requisition
• A query object is a Java object, constructed using methods in the interface AQLStatement. For example:
AQLQuery query = new AQLQuery("Requisition", ListUtil.list("Name"));

These two examples create the same query. In general, you use the Java form if you want to add to the query
from the logic of your Java code, and the string form if you are reading a query string from external files,
such as metadata XML files. You can also combine the two approaches; for example, you could parse a
query string to obtain an initial query, and then add to it programmatically.

Given either form, you can convert to the other easily:


• Given a query object, you can use object.toString() to retrieve a string representation.
• Given a query string, you can call AQLQuery.parseQuery to obtain the equivalent object representation

Building a String Query


To build an AQLQuery object from a string, you construct the literal string and call AQLQuery.parseQuery to
parse the query string and return an AQLQuery object. For example, to construct the following query:

SELECT Name FROM Country


WHERE Name LIKE ‘pattern1’ AND LocaleID.Name LIKE ‘pattern2’

You would type:

String text = "SELECT Name " +


"FROM ariba.basic.core.Country " +

12 Ariba Spend Management Query API Guide


Chapter 2 Ariba Query API Constructing a Query

"WHERE Name LIKE ‘pattern1’ AND " +


"LocaleID.Name LIKE ‘pattern2’ ";
AQLQuery query = AQLQuery.parseQuery(text);

The query string uses a SQL-like language, which is described in detail in “Query Language Details” on
page 27.

You can include values in the query string in any of the following ways:
• As literals:
"SELECT Name FROM Address WHERE Name = 'B%'"

• By calling Fmt.S to do a formatted string (“printf-style”) substitution:


Fmt.S("SELECT Name FROM Address WHERE Name = '%s'", aName)

For more information on the Fmt class, see the Javadoc.


• As named parameters (preceded by a colon):
"SELECT Name FROM Address WHERE Name = :aName"

When you include a named parameter in a query, you pass the value for that parameter in as an option to
the query. For example, in this case, you would pass a value for aName as a query parameter.
For information on specifying parameters to queries, see “Specifying Query Options” on page 14.

Building a Query with Java Methods


To construct a query from the Java API, you use methods in the classes AQLStatement and AQLQuery. For
example, to construct the same query as in the previous example:

AQLQuery query = new AQLQuery


("ariba.basic.core.Country", ListUtil.list("Name"));
query.andLike("Name", pattern1);
query.andLike("LocaleID.Name", pattern2);

This approach is typically more appropriate in cases where the query is built up in pieces in different parts of
the code.

For examples of constructing queries using Java methods, see “Query Examples” on page 24. For a complete
list of the methods that are available for you to use in building queries, see the Javadoc.

Adding Conditions to a Query


When you are building a query from Java code, you can add additional constraints to the query, based on the
logic of your application. For example, you could add a constraint such as WHERE Requester.Name = ? or x.b
BETWEEN 10 AND 20.

One way to build a condition is by parsing a string. For example:

String conditionText =
"(Description.CommonSupplier NOT IN " +
"(SELECT CostCenterToSupplier.Supplier.CommonSupplier"+
"FROM ariba.core.CostCenterToSupplier " +
"PARTITION %s SUBCLASS NONE " +
"WHERE CostCenterToSupplier.CostCenter = %s))";

conditionText = Fmt.S( conditionText,

Ariba Spend Management Query API Guide 13


Executing Query Statements Chapter 2 Ariba Query API

partition.getName(),
AQLScalarExpression.buildLiteral(costCenter).toString());

return AQLCondition.parseCondition(conditionText);

From the Java API, you add conditions with methods in subclasses of AQLCondition. The AQLCondition class
itself is an abstract class, with subclasses such as AQLBetweenCondition and AQLOrCondition that implement
specific conditions.

For more information on the classes and methods in this example, see the Javadoc.

Executing Query Statements


Once you have constructed a query, you use methods in BaseService to operate on that query. The
BaseService API defines the methods validate, executeQuery, and executeUpdate:

• validate performs semantic validation on an AQLStatement


• executeQuery executes a specified query and returns an AQLResultCollection
• executeUpdate modifies a database table, calling a SQL update statement

These methods take a query as argument, and operate on that query. With executeQuery or executeUpdate,
you can supply options, expressed as a parameter of type AQLOptions. When you call executeQuery or
executeUpdate, the Ariba Query API implicitly validates the incoming query. You can also explicitly validate
a query with a call to the validate method.

The rest of this section describes how to set up query options and how to run an execute or update statement.

Note: The BaseService API also includes other methods related to running queries; for a complete list of
available methods, see the Javadoc.

Specifying Query Options


The executeQuery and executeUpdate methods take two arguments: a query object (or string), and an object
of type AQLOptions. You use the AQLOptions parameter to supply parameters to the execute or update
statement.

The AQLOptions class provides the following constructors for options objects:
• AQLOptions(Partition)
• AQLOptions(Partition[])
• AQLOptions()

The first form is the simplest form. You create an AQLOptions object, passing the partition to the constructor.
The rest of the information is retrieved from the user session.

The second form is similar, except that you pass an array of partitions, rather than just a single partition.

With the last form, you create an AQLOptions object, but don’t supply an explicit partition. With this form,
you have to either supply the partition later, or supply it on each individual call.

Once you have constructed an AQLOptions object, you can call methods in the AQLOptions class to set your
preferred options. For example, you can set a locale using the method setUserLocale. For a list of the
available methods that you can use to add options to your AQLOptions object, see the Javadoc.

14 Ariba Spend Management Query API Guide


Chapter 2 Ariba Query API Executing Query Statements

Using AQLOptions for Parameters


You can use an AQLOptions object to specify the actual parameters to be passed to formal parameters that you
specified as named parameters in a literal string query. For example, suppose you have a query string that
includes a named parameter myParam (named parameters are preceded by a colon):

"SELECT Name FROM Address WHERE Name like :myParam"

You supply a value for this parameter and add it to your AQLOptions object as follows:

AQLOptions options;
Map paramMap = MapUtil.map();
paramMap.put("myParam", "R%");
options.setActualParameters(paramMap);

When the query is executed, the information is substituted from the map into the query. You can supply the
actual parameters either as a list or as a map — you use a list if your parameters are numbered, and a map
otherwise.

For a complete list of the available methods for setting values in AQLOptions objects, see the Javadoc.

Using AQLOptions for Result Callback


The AQLOptions object can include a resultCallback parameter, which names a Java class that will be
called to process the results before they are returned. A callback must be an implementation of the interface
ariba.base.core.aql.AQLResultCallback. For more information, see the Javadoc.

Validating a Query
You call the validate method to check a query. The method signature is as follows:

void validate (AQLStatement statement, AQLOptions options)


throws AQLValidateException

This method performs semantic validation on the specifiedstatement. If an error is found, validate throws
an AQLValidateException describing the error.

The Ariba Query API also validates each query just before executing it.

Executing a Query
You use executeQuery to execute a query once you have constructed it. The BaseService API includes two
versions of this method: one that takes a query string as argument and one that takes a query object. The
method signatures are as follows:

AQLResultCollection executeQuery
(AQLStatement statement, AQLOptions options)

This method executes the specified statement, passing in any options defined in the options parameter.

AQLResultCollection executeQuery
(String statementText, AQLOptions options)

This method takes a query string as argument, parses and validates it, performs any substitutions,
generates an AQLStatement, and executes that query statement.

Ariba Spend Management Query API Guide 15


Processing Results Chapter 2 Ariba Query API

For example:

AQLQuery query =
AQLQuery.parseQuery("SELECT req, Preparer.Name " +
"FROM ariba.procure.core.Requisition req " +
"WHERE Preparer.Name = :1 " +
"ORDER BY Name");

AQLOptions options = new AQLOptions(partition,false);


options.setActualParameters(ListUtil.list(user.id));

AQLResultCollection resultCollection =
Base.getService().executeQuery (query, options);

Executing an Update
You execute an update statement by calling executeUpdate, passing either a string query or a statement
object. The resulting code calls a SQL update statement, which modifies a database table. You can update
either a class or a database table. The method signatures for update operations are as follows:

int executeUpdate
(String statementText, AQLOptions options) throws AQLException

int executeUpdate
(AQLStatement statement,
AQLOptions options)
throws AQLException

These methods execute a modification statement, and return the number of objects modified (possibly
zero).

To perform an update, you must explicitly set the options you pass to the executeUpdate method to have
write access, for example:

AQLOptions options; // assume this exists


options.setSQLAccess(AQLOptions.AccessReadWrite);
// assume the String queryStatement exists.
try {
int modified =
Base.getService().executeUpdate(queryStatement, options);
}
catch (AQLException e) { ... }

Update capability is restricted. The update statement must generate SQL that refers to only one table. (A
SQL update statement can only refer to one table in the FROM clause.) This restriction is enforced at query
validation time. Use extreme caution when using update statements.

Processing Results
A call to executeQuery returns an AQLResultCollection object. To process results you first check for errors,
and then access each of the results in the result object. You must check for errors before trying to process
results: if a result object contains errors and you make any call on it aside from checking for errors, the result
is a fatal error.

The classes for result set processing are as follows:


• AQLResultCollection

16 Ariba Spend Management Query API Guide


Chapter 2 Ariba Query API Processing Results

• AQLResultField
• AQLError

The AQLResultCollection class defines the result collection object, and most methods for accessing the
result collection. AQLResultField defines methods for accessing metadata about a result (such as its type),
and AQLError defines a method you can call to access the string representation of an error.

Checking Errors
To process results, you first check for errors. The AQLResultCollection class defines two methods for
checking errors:

List getErrors ()

Returns a list of AQLError objects, or null if there are no errors.

AQLError getFirstError ()

Returns the first error in the list of AQLErrors, or null if there are no errors.

If there were errors, you access the error text with AQLError.toString. For example:

AQLResultCollection results;
if (results.getErrors() != null) {
System.out.println(results.getFirstError().toString());
}

Accessing Results
After checking for errors, you process the AQLResultCollection. The API uses a cursor-based model. You
move through the results with AQLResultCollection.next, which returns true if there is a next row and false
otherwise.

Once on a new row, you can access a specific column with methods in AQLResultsCollection. For example:
• To access fields, use getField
• To access cluster roots, use getBaseID and then dereference the ID
• To access other data (including embedded objects), use getObject

Each of these methods allow you to specify the value either by name or by position. For example, the
getField method has two forms, one that takes an integer and one that takes a string argument. The
following is a simple example:

// Iterate over all fields and print out string value


while (results.next()) {
for(int i = 0; i < results.getResultFieldCount(); i++) {
if(results.getObject(i) != null)
System.out.println(results.getObject(i).toString());
}
}

This example accesses the object by position, using i as the index, and then converts the object to a string.
You can also access an object by column name. For example:

// Access an object’s value by the associated column name


results.getString("Phone");

Ariba Spend Management Query API Guide 17


Processing Results Chapter 2 Ariba Query API

You can use getObject for any type. For example, you can use it to retrieve a BaseObject, such as Money. To
fetch cluster roots, use getBaseId and then call objectFromId on the baseID. For example:

String queryText = "select AlumniDonor from test.ariba.base.core.AlumniDonor";


AQLQuery query = AQLQuery.parseQuery(queryText);
AQLOptions qOptions = new AQLOptions(partition);
AQLResultCollection results =
Base.getService().executeQuery(query, qOptions);

// check for errors in results....


if (results.getErrors() != null) {
// do error handling
}
// should have exactly one result
if (!results.next()) { .... }

ClusterRoot donor2 =
(ClusterRoot)Base.getSession().objectFromId(results.getBaseId(0));
....

For a complete list of the methods in AQLObjectCollection that you can use to fetch back data from your
results, see the Javadoc.

Accessing Metadata
To determine the data type of a result object, you can call AQLResultsCollection.getField to return an
AQLResultField object, through which you can access metadata about a column.

The metadata about the columns in an AQLResultCollection is contained in an AQLResultField object. An


AQLResultField represents a description of a single field (column) in the result set returned from a query.

AQLResultField includes methods such as getType, getClassName, and getName. (For a complete list of the
available methods, see the Javadoc.) None of the methods take any arguments; they each simply return a
piece of metadata about the field. For example:

String getName ()

Returns the name of the result field (the column name).

The following is a simple example that illustrates getName and getClassName:

// Get the class name of the column’s data type


results.getField(0).getClassName();

// Get the column’s name


results.getField(0).getName();

AQLError Class
The AQLError class provides information about errors that occur when a query fails. An AQLError object
contains information on one error. AQLError includes this method:

String toString ()

Returns a string representation of the error.

18 Ariba Spend Management Query API Guide


Chapter 3
Writing Queries

When you write a query statement using the Ariba Query API, you express that query in terms of the object
model. The Ariba Query API interprets your queries and generates SQL, adding appropriate defaults and
translating object model syntax. For example, if you write a query to return all requisitions from the
database, the Ariba Query API automatically filters that query to remove any requisitions that are inactive or
have been purged.

This chapter describes how to write queries with Ariba Query API. It includes the following sections:
• “Common Defaults for Queries” on page 19
• “Query Examples” on page 24
• “The Query Result Cache” on page 25

Common Defaults for Queries


This section describes how the Ariba Query API translates the queries you write, which use object model
and metadata XML terminology, into database queries. It summarizes the default filters added by Ariba
Query API, and also describes how Ariba Query API handles metadata XML simplifications like field
aliases.

Filtering for Active Objects


When you run a query, the Ariba Query API adds implicit WHERE clauses that remove any objects that are
marked in the database as either inactive or marked to be purged. For example, consider the following Ariba
Query API query:

SELECT EmailAddress FROM ariba.user.core.User

This query generates the following additional WHERE clauses to filter out inactive and purged objects:

SELECT Use1.us_EmailAddress
FROM UserTab Use1
WHERE (Use1.us_Active = 1) AND
(Use1.us_Purgedtate = 0 OR Use1.us_PurgeState IS NULL)

To include inactive objects in your query, you can add an explicit active/inactive clause, as described in
“Restricting by Inactive Objects” on page 40.

Purged objects are never accessible through queries.

Filtering by Partition
A query can include one or more partitions, to retrieve only objects in that partition. In general, specifying a
partition yields the same data users see in that partition, in the user interface.

Ariba Spend Management Query API Guide 19


Common Defaults for Queries Chapter 3 Writing Queries

If you are querying on a partitioned class, the partition argument is required. You can specify it in your query
options object, or in the query itself. The Ariba Query API uses that partition information to add a partition
clause to the query. For example, consider the following query:

SELECT EmailAddress FROM ariba.user.core.User

This query generates the following SQL:

SELECT Use1.us_EmailAddress
FROM UserTab Use1
WHERE (Use1.us_Active = 1) AND (Use1.us_PurgeState = 1) AND (Use1.us_PartitionNumber = 0 OR
Use1.us_PartitionNumber = 2)

Partition 0 is unpartitioned data, and Partition 2 (in this example) is the partition you have specified in your
query options object. If you are querying on a partitioned class, the query filter always includes
unpartitioned data (Partition 0) as well.

For information on how to specify the partition directly in the query, or query across partitions, see
“Restricting by Partition” on page 40.

Filtering for Locale


Most string fields in metadata XML are of type MultiLingualString, which means that the field can have
multiple translated values, one per language. When you write queries, you can reference a multilingual
string field as if it were a string, and the Query API returns an appropriate translation of that string.

For example, if TestLanguage is a class with a field called TranslatedStrings which is a multilingual string,
the following query selects just one string translation:

SELECT TranslatedStrings FROM TestLanguage

When you write queries that access fields of type MultiLingualString, both locale and partition are required
in the AQLOptions. Ariba Query API returns the translation appropriate for the specified partition. If the
language of the partition cannot be determined (if the partition is Any, or there are several partitions with no
common language), Ariba Query API uses the user’s preferred language instead.

Accessing Data through Field Aliases


Metadata XML supports the concept of field aliases, which are aliases defined in metadata XML. Field
aliases support dot notation, so it’s possible to rename a field and still access it from the original name in the
metadata, if there is an appropriate field alias defined. For example, a field is moved or renamed for some
reason, a field alias can be added that aliases the old field name to the new location.

Because the Query API reads and parses the metadata, you can write queries that use field aliases. The
Query API is able to follow any such field aliases and reach the underlying field. You do not have to do
anything special in your query to indicate that you are using an alias.

20 Ariba Spend Management Query API Guide


Chapter 3 Writing Queries Common Defaults for Queries

Accessing Vectors
Ariba Spend Management applications store vectors in separate vector tables. The object model supports
both direct and indirect vectors. A vector of ‘direct’ uses a direct join between the ClusterRoot table and the
BaseObject table. A vector of ‘indirect’ joins through the BaseId table. You can use the same query to access
either a direct or indirect vector. The Ariba Query API determines the appropriate vector table for you and
queries that table.

Accessing Normalized Tables


Database normalization is the process of organizing data efficiently in a database, to eliminate redundancy
and help ensure that related data is stored together.

When you write queries that access your database, you do not need to know the database layout, or which
classes have been normalized. The Ariba Query API checks the metadata XML to determine which classes
are normalized, and then constructs the query as appropriate.

For example, in Ariba Buyer, the Approvable hierarchy is normalized, which means that Ariba Buyer creates
a separate table for data that is shared by that class and its subclasses. This normalization makes it more
efficient to query on Approvable, which has a large number of subclasses. A query on Approvable need only
query that shared table, and does not need to join all the subclasses. Thus, this query:

SELECT Name, ShipTo FROM ariba.procure.core.Requisition

Generates the following SQL:

SELECT App1.ap_Name, Req2.re_ShipTo


FROM ApprovableTab App1,
RequisitionTab Req2
WHERE App1.rootId = Req2.rootId AND
(App1.ap_Active = 1) AND
(App1.ap_PartitionNumber = 0 OR App1.ap_PartitionNumber = 2)

However, the Address hierarchy is not normalized, so a similar query on that class translates to a query that
joins the individual tables by name. For example, consider this query:

SELECT Name FROM ariba.basic.core.Address

This simple query generates the following SQL:

SELECT v2_1.ad_Name
FROM v2_AddressTab v2_1
WHERE (v2_1.ad_Active = 1) AND
(v2_1.ad_PartitionNumber = 0 OR v2_1.ad_PartitionNumber = 2)
UNION ALL
SELECT v2_1.sl_Name
FROM v2_SupplierLocationTab v2_1
WHERE (v2_1.sl_Active = 1) AND
(v2_1.sl_PartitionNumber = 0 OR v2_1.sl_PartitionNumber = 2)
UNION ALL
SELECT v2_1.puoa_Name
FROM v2_PunchOutAddressTab v2_1
WHERE (v2_1.puoa_Active = 1) AND
(v2_1.puoa_PartitionNumber = 0 OR v2_1.puoa_PartitionNumber = 2)

When you write queries using the Ariba Query API, you write the simple query and let the Ariba Query API
determine which tables are involved and create any necessary join statements.

Ariba Spend Management Query API Guide 21


Common Defaults for Queries Chapter 3 Writing Queries

Using Dot Notation in Queries


You can use dot notation in Ariba Query API statements. The Ariba Query API follows the designated path
to find the associated field, and does an implicit auto-join, if necessary. The auto-join used in dot notation is
usually an inner join. If you need an outer join, you have to specify the joins explicitly in the query, and
cannot use dot notation.

In the following example, TaxAmount is a field in Requisition that embeds a money object (a direct reference
to Money), and Preparer is a field in Requisition that refers to a User object (an indirect reference to User).

Following is the Ariba Query API query:

SELECT Preparer.Name, TaxAmount.Amount


FROM ariba.procure.core.Requisition

This query generates the following SQL:

SELECT Use1.us_Name, Req3.mo0_Amount


FROM ApprovableTab App2,
RequisitionTab Req3,
UserTab Use1
WHERE App2.rootId = Req3.rootId AND
App2.ap_Preparer = Use1.rootId AND
(App2.ap_Active = 1) AND
(App2.ap_PartitionNumber = 0 OR App2.ap_PartitionNumber = 2) AND
(Use1.us_Active = 1) AND
(Use1.us_PartitionNumber = 0 OR Use1.us_PartitionNumber = 2)

In this example, the amount field is referenced directly in the row of RequisitionTab, but the preparer name
requires a join to the User table. When you use the Query API, you do not need to know whether an object
embeds another (a direct reference) or refers to it (an indirect reference).

Note, however, that the implicit inner join means that you cannot use dot notation in OR queries. For example,
consider the following query:

select "User".Name from "User" where


"User".Roles.Permissions in (BaseId('6bc.5o'),BaseId('690.50'))
OR "User".Permissions in (BaseId('6bc.5o'))

In this query, the use of dot notation in User.Roles and User.Permissions means that Ariba Query API
always does an inner join, selecting only those users with both the specified role and the specified
permission. The OR query has no effect, since the inner join selects only rows that have both the specified
row and the specified permission. To write an OR query, you cannot use dot notation.

Note that User is in quotation marks because it is a reserved word. For a list of reserved words, see
“Reserved Words” on page 67.

Using Dot Notation in From Clauses


You can use auto-joined fields (dot notation) in a FROM clause. For example, consider the following query:

SELECT prep.Name FROM Requisition.Preparer prep


WHERE prep.Name LIKE ‘N%’

This query behaves as though it had been written as follows:

SELECT prep.Name FROM Requisition, “User” prep


WHERE prep.Name LIKE ‘N%’ AND

22 Ariba Spend Management Query API Guide


Chapter 3 Writing Queries Common Defaults for Queries

Reqisition.Preparer = prep

This query could also be written as follows:

SELECT Requisition.Preparer.Name FROM Requisition


WHERE Requisition.Preparer.Name LIKE ‘N%’

Or, since Preparer is unique within the FROM list, it could be written as follows:

SELECT Preparer.Name FROM Requisition


WHERE Preparer.Name LIKE ‘N%’

In general, this notation:

FROM A.f AS x

is shorthand for the following options, which are the defaults:

FROM A INCLUDE ACTIVE


EXCLUDE INACTIVE
INCLUDE NOTPURGED
PARTITION my_partition
SUBCLASS ANY
AS A
INNER JOIN
B INCLUDE ACTIVE
INCLUDE NOTPURGED
EXCLUDE INACTIVE
PARTITION my_partition
SUBCLASS ANY
AS x
USING f

Using Vector Auto-Joins in From Clauses


You can also do auto-joins to vector fields in the FROM clause. For example, this query returns the names of
Users with the Catalog Manager role:

SELECT "User".Name from "User".Roles “role”


WHERE “role”.Name = ‘Catalog Manager’

Is equivalent to:

SELECT "User".Name from "User", "Role" “role”


WHERE “role”.Name = ‘Catalog Manager’ AND
"User".Roles = “role”

Metadata XML Settings Affecting Queries


The Ariba Query API uses the declarations from metadata XML files to determine which data is available in
the database. From the metadata XML, certain attributes and elements directly affect whether information is
available in queries. For example, the metadata XML can specify whether fields or classes are persisted to
the database (and thus available for querying).

The following metadata XML tags and attributes affect whether a given object or field is returned in a query:
• The noSchema attribute of a <class> declaration. If a class is declared with the attribute noSchema=true,
objects of that class are not stored in the database, and so cannot be returned in queries.

Ariba Spend Management Query API Guide 23


Query Examples Chapter 3 Writing Queries

• The <derived> tag. If a field is declared as a <derived> element, the value of that field is computed
dynamically and not stored in the database. You cannot query for the value of derived fields.
• The noPersist attribute of a <field> declaration. If a class is declared with the attribute noPersist=true,
the data for that field is not stored in the database, and so cannot be returned in queries.
• The noQuery attribute of a <field> declaration. If a field is declared with the attribute noQuery=true, the
data for that field is stored in the database, but not returned in query results.

Query Examples
This section shows examples that illustrate how to construct query objects, using both AQLQuery methods and
query strings.

Auto-Join Example
The queries in this example look for requisitions where the Preparer.Name field matches a specified value,
and return the base IDs and names of those requisitions, ordered by Requisition name. This query illustrates
how the Ariba Query API implements the dotted path notation with an automatic implicit inner join.

This example includes the call to actually execute the query. This is omitted from the remaining examples.

Java API AQLQuery query =


new AQLQuery('ariba.procure.core.Requisition');
query.addSelectElement("Name");
query.addOrderByElement("Name");
query.andEqual("Preparer.Name", value);

AQLResultCollection result = Base.getService().executeQuery


(query, options);

Query String AQLQuery query =


AQLQuery.parseQuery("SELECT req, Preparer.Name " +
"FROM ariba.procure.core.Requisition req " +
"WHERE Preparer.Name = :1 " +
"ORDER BY Name");
options.setActualParameters(ListUtil.list(value));

AQLResultCollection resultCollection =
Base.getService().executeQuery (query, options);

Vector Example
This example illustrates queries that look for users with a specific role. It returns the base IDs of Users who
have the role given by the String object roleName.

Java API AQLQuery query =


new AQLQuery('ariba.user.core.User.Roles');
query.setSelectList(new AQLFieldExpression("User"));
query.andEqual("Name", roleName);

Query String AQLQuery query = AQLQuery.parseQuery("SELECT "User" " +


"FROM "User".Roles " +
"WHERE Roles.Name = :roleName");

24 Ariba Spend Management Query API Guide


Chapter 3 Writing Queries The Query Result Cache

The Query Result Cache


The Ariba Query API provides a cache which can be used to cache the results of previously-executed
queries. Using the cache improves performance for queries that have static data, such as queries on data from
integration events. For example, a query that retrieves all available currencies is a good candidate for result
caching, since it returns the same result each time it is run. However, a query that involves user parameters
(such as “find me all requisitions I submitted in the last week”) is not a good candidate for caching, since the
result set is different each time the query is run.

When the result cache is enabled and a query is executed, the query result cache is checked to see if that
query has been executed before. If it has been, the previous results are returned.

The result cache is purged when it overflows, when an integration event runs, or when a multiserver node
rejoins the node group. When you write a query that uses the cache, it is your responsibility to ensure that it
is safe to use cached results.

Using the Cache


Each query includes a Boolean option to indicate whether the results of that query should be included in the
cache. (Note, however that enabling the query cache is just a hint, since for some queries, the hint may be
ignored.)

To specify whether you want the results of a query to be cached, you set parameters in the AQLOptions object.
By default, the cache is disabled. To enable the cache, use the method AQLOptions.setUseCache.

Using the Cache with a Nametable


A nametable is a Java class that runs a database query to retrieve data that is used to populate a chooser.
When you write a nametable, you can specify whether the results of the query should be cached.

Custom nametables are usually subclasses of ariba.base.core.AQLNameTable.When you write a custom


nametable that subclasses AQLNameTable, the standard way to set the cache option for that nametable is by
calling AQLNameTable.buildOptions.

The method signature for buildOptions is as follows.

public AQLOptions buildOptions (String field, String pattern)

This method constructs an AQLOptions object and returns that object, with appropriate options set. The
field and pattern parameters represent the information that the user has entered in the chooser. For
example, if a user searches for “Janic*,” the pattern field will be set to Janic*.
This method calls AQLNameTable.updateIgnoreCache, which disables the query cache whenever the user
has set up a custom query, or a query that includes user-created objects.

For situations where you want more control over the creation of the AQLOptions objects, you can also call
AQLNameTable.updateIgnoreCache directly.

Note that the AQLNameTable class does not cache queries if the includesUserObjects property is set to true. In
this case, it ignores any setting in your AQLOptions object.

Ariba Spend Management Query API Guide 25


The Query Result Cache Chapter 3 Writing Queries

Configuration Settings for the Cache


In Ariba Buyer, you can use the System.Performance.QueryCacheSize parameter to specify the number of
entries to allocate in the query cache. In the default configuration of Ariba Buyer, this parameter is set to 70.

26 Ariba Spend Management Query API Guide


Chapter 4
Query Language Details

This chapter provides a detailed description of the Ariba Query API query language. The query language is
a subset of a standard known as the Object Query Language, with a few Ariba-specific extensions, such as
syntax to specify Ariba partitions.

This chapter includes the following sections:


• “Syntax Conventions” on page 27
• “Terminal Symbols” on page 28
• “Data Types” on page 32,
• “Annotated Grammar” on page 32
• “Known Limitations” on page 66

Syntax Conventions
This section describes the syntax conventions for the language grammar used in this chapter. In general,
punctuation symbols indicate syntax conventions; for example, * represents 0 or more occurrences of a
symbol. However, when a punctuation symbol appears in bold, you must type that symbol in your query
string. If you are not sure whether you should type a symbol, check the example for guidance.

Convention Description
nonterminal Non-terminal symbols are in lowercase.
::= This symbol introduces a production.
KEYWORD Terminal name symbols that are keywords (reserved) are in
all caps.
FunctionName Terminal name symbols that are not keywords (not
reserved) are in italics, mixed case.
<string_literal> A terminal symbol.
[ ] Surrounds optional elements.

Bold square brackets represent a vector substring. You


must type them in your query string.
| Indicates an ‘either-or’ choice.
( ) Groups related elements, as in ( AND | OR ).

Bold parentheses enclose function arguments. You must


type them in your query string.

Ariba Spend Management Query API Guide 27


Terminal Symbols Chapter 4 Query Language Details

Convention Description
* Indicates zero or more occurrences of the preceding
element.

A bold asterisk represents the multiplier symbol. You must


type it in your query string.
+ Indicates one or more occurrences of the preceding
element.

A bold plus sign represents the unary addition symbol. You


must type it in your query string.

Terminal Symbols
This section describes the terminal symbols used by Ariba Query API:
• Keywords
• Operators
• Punctuation
• Identifiers
• Literals

Keywords
Keywords are case-insensitive. The following names are reserved, and cannot be used as identifiers unless
they are quoted (delimited with double quotes) or follow a period (.) as in a field path, as described in
“Identifiers” on page 30.

Function names are not reserved words, except those that are already SQL92 reserved words. Ariba Query
API includes the following keywords:

ACTIVE ALL AND ANY AS


ASC AVG BETWEEN BY CASE
COALESCE CONTAINS COUNT DATE DAY
DELETE DESC DISTINCT END ESCAPE
EXCLUDE EXISTS FALSE FROM GROUP
HAVING IN INACTIVE INCLUDE INDEX
INNER INSERT INTO IS JOIN
LEFT LIKE LOWER MAX MIN
MONTH NONE NOT NULL OBJECT
ON OR ORDER OUTER PARTITION
POSITION RIGHT ROUND SELECT SET
SOME STDEV SUBCLASS SUBSTRING SUM
THEN TRUE UNION UPDATE UPPER
USING VALUES VARIANCE VARIANT WHEN
WHERE YEAR

28 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Terminal Symbols

In addition, Appendix A, “Reserved Words,” lists words that are not currently used but are reserved now as
keywords for possible future use.

Operators
Ariba Query API includes the following operators:

Operator Description
= == equality
< less than
<= less than or equal
> greater than
>= greater than or equal
<> != inequality
| bitwise or
& bitwise and
+ binary addition, unary positive
- binary subtraction, unary negative
|| concatenation
* multiplication
/ division
. field selection
() function call arguments/expression grouping
[] vector subscript

Other Punctuation
Ariba Query API includes the following additional punctuation:

, general separator
: parameter marker

Ariba Spend Management Query API Guide 29


Terminal Symbols Chapter 4 Query Language Details

Identifiers
The following are valid identifiers in Ariba Query API:

class_alias ::= <identifier>


class_name ::= <identifier>
field_alias ::= <identifier>
field_name ::= <identifier>
index_name ::= <identifier>
parameter_name ::= <identifier>
partition_name ::= <identifier>
table_name ::= <identifier>
table_alias ::= <identifier>
variant_name ::= <identifier>

Identifiers must be legal Java identifiers. Identifiers are case-sensitive.

To use a keyword or reserved work as a identifier, surround it in double quotes. For example:

SELECT "User".Name

Also, for convenience, any identifier following a period is treated as if it were in quotes. A reserved
word/keyword cannot be used as an identifier unless it is quoted or it follows a period (.) in a field path.

Function names are case-insensitive, for usability.

Literals
This section describes the grammar for expressing literals in Ariba Query API.

Integer literals
An integer literal is defined as follows:

<integer_literal> ::=
0 | non_zero_digit digit*

non_zero_digit ::=
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

digit ::=
0 | non_zero_digit

Floating point literals


A floating point literal is defined as follows:

<floating_point_literal> ::=
digit+ . digit* [ exponent ] |
. digit+ [ exponent ]

30 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Terminal Symbols

exponent ::=
( e | E ) [ + | - ] digit+

String literals
String literals are delimited by single quotes, and are case-sensitive. To include a single quote in a string
literal, double the quote. For example:

‘Don’’t forget to double internal quotes!’

Date literals
In general, you use Date objects to express dates, although Ariba Query API also supports date literals.
Internally, dates are represented in GMT, and functions that return date values return those values in GMT.

To create a date from a literal, you can use Date or CalendarDate. Both can convert from literals to dates,
using the same format to describe the date. The only difference is that the Date function requires a timezone,
and the CalendarDate function does not.

The following examples illustrate the use of Date and CalendarDate:

SELECT SubmitDate FROM Requisition


WHERE SubmitDate >= Date('2002-09-04 13:12:28 PDT')

SELECT StartingDate FROM ExpenseReport


WHERE StartingDate >= CalendarDate('2002-10-22 00:00:00')

Select Requisition from ariba.procure.core.Requisition


where LastModified < date('2004-01-13 PST')

The date format is based on the format used in SQL and IBM DB2. The format is as follows:

Regular date 'yyyy-MM-dd [[HH:mm]:ss] zzz'

Calendar date 'yyyy-MM-dd [[HH:mm]:ss]'

The terms used in these formats are as follows:


• yyyy — year
• MM — month
• dd — day
• HH — hour
• mm — minutes
• ss — seconds
• zzz — time zone

BaseID literals
In general, you use BaseID objects to express BaseIDs. However, you can also specify BaseID literals with
the BaseId built-in function, which parses a string representation of the BaseID. For example:

SELECT PurchaseOrder FROM PurchaseOrder WHERE PurchaseOrder=BaseId('1234.ab')

Ariba Spend Management Query API Guide 31


Data Types Chapter 4 Query Language Details

Data Types
Ariba Query API supports the data types used in metadata XML:

Type Description
Boolean java.lang.Boolean

int, long Including java.lang.Integer and java.lang.Long. These


are INTEGER types.
double Including java.lang.Double and java.math.BigDecimal.
With the INTEGER types, these are the NUMERIC data
types.
String java.lang.String.

Date Subsumes SQL TIMESTAMP, DATE, and TIME.


BaseId An Ariba object ID.
BaseObject An Ariba object.

The associated Java types are declared in the class AQLScalarExpression.

Ariba Query API also supports vectors.

Annotated Grammar
This section provides a complete description of the grammar used by Ariba Query API. It includes the
following sections:
• “Select Statements” on page 32
• “Class and Field References” on page 36
• “Join Clauses” on page 41
• “Conditional Expressions” on page 45
• “Scalar Expressions” on page 52
• “Other Statement Types” on page 58

Select Statements
The Ariba Query API supports the following SQL statement types:
• select
• update
• delete
• create

This section focuses on select statements. Most Ariba Query API statements are select statements. For
information on other statement types, see “Other Statement Types” on page 58.

32 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

Select Statements
A select statement describes data to be read from the database.

Example SELECT Name, Requester.Name FROM Requisition


WHERE Requester.Name = 'Mark Richards'

Grammar select_expression ::=


SELECT [ ALL | DISTINCT ] [ select_list ]
FROM join_term_list
[ WHERE conditional_expression ]
[ GROUP BY field_reference_list ]
[ HAVING conditional_expression ]

Java class AQLSelectExpression extends AQLClassExpression

AQLClassSelect (List joinTermList,


List selectList,
boolean isDistinct,
AQLCondition where,
List groupByList,
AQLCondition having);

The select list describes the field or fields you are selecting. You can specify individual fields or use a
wildcard (*) to specify multiple fields. A select term can be any of the following:
• A simple type, such as string, integer, boolean, date, float, etc. The results list includes the appropriate
data type.
• A BaseObject (stored directly in the database table). The results list includes the BaseObject itself.
• A ClusterRoot (or other field declared explicitly as indirect). The result list includes the BaseID for that
BaseObject (not the object itself).

• A wildcard * character. A wildcard can appear after a class reference or on its own:
• If you use a wildcard after a class reference, the query returns all non-vector fields, including inherited
fields. The wildcard select is applied recursively for embedded (direct) classes.

Ariba Spend Management Query API Guide 33


Annotated Grammar Chapter 4 Query Language Details

• If you use a wildcard alone, it must be the only element in the select list. It is interpreted as though it
were applied to each class reference in the FROM clause.

Example 1 SELECT req.Name, req.Requester.Name


FROM ariba.procure.core.Requisition req

SELECT Name, Requester.Name


FROM ariba.procure.core.Requisition req

These statements are equivalent. Each returns a vector of elements,


where each element is an object array whose elements are Strings. The
first string is the requisition name and the second is the requester name.
Example 2 SELECT Requester.*
FROM ariba.procure.core.Requisition req

Returns a vector of elements where each element is an object array


containing all of the fields from Requester.
Example 3 SELECT TaxAmount
FROM ariba.procure.core.Requisition req

Returns a vector of elements, where each element is an object array


containing a Money object (since TaxAmount is a direct reference to
Money).
Example 4 SELECT req, LastModified
FROM ariba.procure.core.Requisition req

Returns a vector of elements, where each element is an object array


whose first element is the BaseId of a Requisition object, and whose
second element is a Date object.
Grammar select_list ::=
select_list_element ( , select_list_element )*

select_list_element ::=
[ field_reference . ] *
| scalar_expression [ [ AS ] field_alias ]

Java class AQLSelectListElement extends AQLNode

AQLSelectListElement (AQLScalarExpression expr,String


fieldAlias);

Notes and restrictions on select statements:


• GROUP BY is only supported for cases where the grouping can be done by the database. GROUP BY statements
that involve a SQL union are not supported and generate validation errors.
• It is an error to query for BaseObjects in a vector, if those BaseObjects are not ClusterRoots. For example,
the following select statement generates an error:
Select LineItems from Requisition

However, it is possible to select fields in BaseObject itself, which is the more common case.
• You cannot query on fields of type ariba.base.core.LongString. LongString is a BaseObject that breaks a
string into chunks of 254 characters or less. You can't query it like a String field because the data is stored
in multiple rows in the database.

34 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

• You cannot query directly on fields of type ariba.util.core.Blob, because the results of such a query are
potentially huge. A query such as SELECT BlobField.BlobField FROM
test.ariba.base.core.ObjectWithLob generates a validation error.

• If you omit the select_list, the default select list is the base ID of the first class in the join_term_list.

Using the Union Operator


A class_expression is a select expression, with an optional UNION operator.

Grammar class_expression ::=


class_primary
| class_expression union_operator class_primary

Java class AQLClassExpression extends AQLNode

class AQLClassUnion extends AQLClassExpression

AQLClassUnion (AQLClassExpression leftClassExpr,


int op,
AQLClassExpression rightClassExpr);

You use the UNION operator to union two select lists. UNION eliminates duplicates. UNION ALL does not. The
select lists must have the same number of elements, and corresponding positions must be type-compatible.

Example SELECT a, b FROM x


UNION ALL
SELECT c, d FROM y

Grammar union_operator ::=


UNION
| UNION ALL

Java (from class AQLClassExpression)

static final int AQLClassOpUnion = 1;


static final int AQLClassOpUnionAll = 2;

The Ariba Query API supports UNION only with SELECT statements.

Ariba Spend Management Query API Guide 35


Annotated Grammar Chapter 4 Query Language Details

Using an Order By Clause


A select statement can optionally include an ORDER BY clause. An order by clause specifies the order of
results in the result list.

Example SELECT Name FROM Country ORDER BY Name

Grammar select_statement ::=


class_expression
[ ORDER BY order_by_list ]

order_by_list ::=
order_by_element ( , order_by_element )*

Java class AQLQuery extends AQLNode

AQLQuery (AQLClassExpression classExpr, List orderBy);

You can specify the field on which to sort either by name (field_reference) or by position
(<integer_literal>). The first column position is 1.

Examples SELECT a FROM x


ORDER BY a

SELECT a, b*c FROM x


ORDER BY 2

SELECT a.b FROM x


ORDER BY a.b

Grammar order_by_element ::=


( field_reference | <integer_literal> ) [ ASC | DESC ]

Java class AQLOrderByElement extends AQLNode

AQLOrderByElement (AQLFieldExpression field);


AQLOrderByElement (int index);

You cannot use a field of type ariba.util.core.Blob in an ORDER BY clause.

Class and Field References


A class reference introduces a class name into a query; a field reference introduces a field name. This section
describes the syntax you can use to name classes and fields from within queries.

Class Reference
A class_reference introduces a class name into a query. The class reference is usually a class name, but
can also be a SQL table or view name. You can specify the class reference in any of the following ways:
• By class name. You can query on any class that is defined as a ClusterRoot. Selecting from a class
produces all instances of that class. To restrict a query to specific subclasses, use the SUBCLASS modifier.
(See “Class Modifiers” on page 39.)
• By class name. You can query on specific fields of a class.

36 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

• By SQL table or view name. In this case, no class modifiers are allowed.

Examples SELECT Country FROM Country


WHERE Name = ‘Canada’

SELECT Country FROM ariba.basic.core.Country c


WHERE c.Name = ‘Canada’

Grammar class_reference ::=


class_name [ [ AS ] class_alias ] class_modifier*
| field_reference [ AS ] class_alias class_modifier*
| table_name [ AS ] table_alias

Java class AQLClassReference extends AQLClassExpression

AQLClassReference (String className);

AQLClassReference (AQLFieldExpression className,


String classAlias,
AQLClassPartition classPartition);

In general, you should use the full class_name (ariba.basic.core.Country) instead of the simple class_name
(Country), to avoid duplicate class name errors. (Even if the simple class name is unique now, later
extensions can always introduce duplication. It’s safest to always use the full class name.)

If you use the field_reference form and you don’t specify an alias, the simple name of the class is the
default alias. For example:

SELECT Country FROM ariba.basic.core.Country


WHERE Country.Name = ‘Canada’

For compatibility with metadata XML field paths, the name ‘this’ (AQLFieldExpression.ThisFieldName) is
reserved as an implicit alias for the first class reference in the FROM list. For example, consider the following
query:

SELECT this.Name from Country c

This query is equivalent to:

SELECT c.Name from Country c

Field References
A field_reference introduces a field name into a query. A field_reference names a field, and can
potentially use dot notation to navigate the object model. When you use dot notation, the left operand of
each ‘.’ must be a class or field of a class type. The far left-most name must be a class_name (or class alias),
although you can omit the class name if the class can be uniquely determined from the names that are in
scope.

Ariba Spend Management Query API Guide 37


Annotated Grammar Chapter 4 Query Language Details

When you use dot notation, as in class.field1.field2, Ariba Query API uses automatic joins to navigate
the implied relationships. Auto-joining always does an inner join (using the same partition, subclass, and
active/inactive information). If you require anything other than the default join type, partition/variant,
subclass or inactive bit, you must use an explicit join, as described in “Join Clauses” on page 41.

Grammar field_reference ::=


simple_name [ vector_subscript ]
| field_reference . simple_name [ vector_subscript ]

Java class AQLFieldExpression extends AQLScalarExpression

AQLFieldExpression (String dottedPath);


AQLFieldExpression (AQLName name);
AQLFieldExpression (AQLFieldExpression pathPrefix,
AQLName name);

There are two cases that are handled specially:


• Fields that are of type multi-lingual string are handled by returning just one translation of the string.
When you reference a field of type ariba.common.core.MultiLingualString, the field reference produces
the String whose translation matches the language associated with the userLocale/userPartition in the
query options object. If there is no such translation, the default is to return the PrimaryString for that
multi-lingual string.
• A field reference can use a field alias, as defined in the metadata XML files. A reference to a field alias is
followed as if it were a reference to the original field.

Name Scope
Each SELECT statement introduces a new name scope. Scopes nest with names in inner scopes, potentially
hiding names in outer scopes. Each class_reference in a query introduces the following names into the
current scope:
• The class name itself, or the alias name if the class_reference has an alias.
• For the first class in the query, the name ‘this’ is introduced automatically as an alias.
• All field names, including inherited fields.

If a field name is uniquely determined in the current scope, you do not need to qualify it with the class name.
However, it is a validation-time error if the field name is ambiguous in the current scope.

Grammar simple_name ::=


field_name
| field_alias
| class_name
| class_alias
| table_name
| table_alias

Java class AQLName extends AQLScalarExpression

AQLName (String name);

38 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

Vector Subscripts
You use a vector_subscript expression to index an expression representing a vector. The subscript must be a
single non-negative integer value, which selects the vector element at that (0-based) position. The only
supported subscript is [0].

This notation is used in field aliases to provide backward compatibility for a field that changed from being
single-valued to being a vector. The original field can be aliased to the first (0th) element of the new vector
field. There are no ‘subscript-out-of-range’ errors. If no element exists for the given index, no element will
match.

Example SELECT User.Roles[0].Name FROM User

Grammar vector_subscript ::=


[ <integer_literal> ]

Class Modifiers
A class reference in a select statement can include one or more optional class modifiers. Class modifiers are
SQL extensions that you use to select data based on Ariba-specific information, such as partitions and active
status.

class_modifier ::=
class_active
| class_inactive
| class_partition
| class_subclass

Restricting by Active Objects


The ACTIVE modifier restricts a query based on whether the objects are marked as active or inactive in the
database. The default is INCLUDE ACTIVE, which means that the Ariba Query API adds the clause AND
(…Active = 1) to the generated query, to ensure that the query selects only active objects. To get only
inactive objects, you would specify EXCLUDE ACTIVE.

Example SELECT Name FROM Requisition INCLUDE ACTIVE

Grammar class_active ::=


INCLUDE ACTIVE
| EXCLUDE ACTIVE

If you are using a statement with auto-join, the auto-join uses the active/inactive information from the class
being joined to. If you want to use different active/inactive information, you must use an explicit join.

The following summarizes the possible combinations:


• The default is INCLUDE ACTIVE EXCLUDE INACTIVE.
• INCLUDE ACTIVE has no effect.
• It is an error to specify either EXCLUDE ACTIVE or EXCLUDE ACTIVE EXCLUDE INACTIVE, since those
expressions specify that the query should not return any data.
• If you specify INCLUDE INACTIVE or INCLUDE ACTIVE INCLUDE INACTIVE, no modifiers are added, and the
query returns all objects (both active and inactive).

Ariba Spend Management Query API Guide 39


Annotated Grammar Chapter 4 Query Language Details

Restricting by Inactive Objects


The INACTIVE modifier specifies how to handle inactive objects. The default for this modifier is EXCLUDE
INACTIVE,which adds AND (…Active = 0) to the generated query.

Example SELECT Name FROM Requisition INCLUDE INACTIVE

Grammar class_inactive ::=


INCLUDE INACTIVE
| EXCLUDE INACTIVE

Restricting by Partition
The PARTITION modifier specifies a partition in which to query for a specified class. If you don’t specify a
partition clause, the default is PARTITION default_partition_name, where default_partition_name is the
default partition from the query options.

If you are querying on a partitioned class, you must specify a partition either in the partition clause or in the
AQLOptions object. If you do not supply the partition clause, and there is no partition in the query options
object, the query results in an error.

Grammar class_partition ::=


PARTITION partition_specifier

partition_specifier ::=
ANY
| NONE
| partition_name
| ( partition_name_list )

partition_name_list ::=
partition_name ( , partition_name_list )*

Java AQLClassPartition extends AQLNode

AQLClassPartition (List partitionNameList);

static final int PartitionAny = 1;


static final int PartitionNone = 2;
static final int PartitionList = 3;
static final int PartitionNotList = 4;

The partition_specifier indicates which partition to search. You can specify the name of an individual
partition, a list of partitions, or the keywords ANY or NONE:
• Partition_name searches the named partition.
• Partition_name_list searches the listed partitions.
• ANY searches objects in all partitions as well as non-partitioned objects.
• NONE searches only non-partitioned objects.

In general, specifying a partition yields the same data users see in that partition, in the user interface. For
example, consider if you query on a partitioned class that has a unpartitioned superclass, the query results
include fields of that partitioned class that are in the unpartitioned superclass.

40 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

The following example illustrates a query using PARTITION ANY:

SELECT POLineItem.Amount.Amount, POLineItem.ShipTo.UniqueName, PurchaseOrder.Supplier.Name FROM


PurchaseOrder AS PurchaseOrder PARTITION ANY INNER JOIN POLineItem AS POLineItem PARTITION ANY
USING PurchaseOrder.LineItems WHERE PurchaseOrder.OrderedDate BETWEEN date('3 Mar 2003 04:00:00
GMT') AND date('1 Apr 2003 03:59:59 GMT')

If you specify a list of partitions, the Ariba Query API cannot determine whether those partitions are in the
same variant. In this case, the query results include only intrinsic fields or extensions of the ‘Plain’ variant.

Including Subclasses in a Query


The SUBCLASS modifier indicates whether to search subclasses of the specified class. You can specify any of
the following values:
• ANY searches the class and all subclasses. This is the default. Only the fields in the class named in the class
reference may be referenced.
• NONE searches only the class, but none of its subclasses. Only the fields in the class named in the class
reference may be referenced.
• subclass_name searches only the listed (sub)class and its subclasses, recursively. This allows access to
fields particular to the listed subclass (but not fields particular to its subclasses). If you specify NOT
subclass_name, the query searches all subclasses except the one named (and its subclasses).

• subclass_name_list searches a list of classes and subclasses, recursively. If the list contains more than one
class, only the fields in the superclass named in the class reference may be referenced. You can specify
NOT (subclass_name_list), to search a list of all subclasses except those named and their subclasses.

Example SELECT Name FROM Approvable SUBCLASS Requisition

SELECT Name FROM Approvable SUBCLASS (Requisition, ExpenseReport)

Grammar class_subclass_list ::=


ANY
| NONE
| [ NOT ] subclass_name
| [ NOT ] ( subclass_name_list )

class_subclass ::=
SUBCLASS subclass_specifier

subclass_name_list ::=
field_reference ( , field_reference )*

Java static final int SubclassAny = 1;


static final int SubclassNone = 2;
static final int SubclassList = 3;
static final int SubclassNotList = 4;

Join Clauses
You use a JOIN clause to express a query that selects from multiple tables. The following is a simple
example:

SELECT User.Name
FROM Requisition JOIN User USING Preparer

Ariba Spend Management Query API Guide 41


Annotated Grammar Chapter 4 Query Language Details

There are often many different ways to express the same query. For example, a SELECT statement that selects
from multiple table does an implicit inner join. You write an explicit JOIN clause only if you want options
that are not the defaults, or if you prefer the JOIN for readability.

For example, because INNER JOIN is the default, these statements are equivalent:

SELECT emp.Name, mgr.Name


FROM User emp INNER JOIN User mgr ON emp.Supervisor = mgr

SELECT emp.Name, mgr.Name FROM User emp, User mgr


WHERE emp.Supervisor = mgr

SELECT User.Name, mgr.Name FROM User.Supervisor mgr

SELECT emp.Name, mgr.Name


FROM User emp INNER JOIN User mgr USING Supervisor

Join Terms
A JOIN clause must have either a USING clause or an ON clause, to specify the list of columns on which you are
doing the join.

The field specified in a USING clause uses a simplified form of dot notation. It must be either a field name
relative to the previous class or in the form of class.field or alias.field. Therefore, the following query:

SELECT Requisition.UniqueName, s.UniqueName


FROM Requisition
JOIN "User" AS s USING Requisition.Requester.Supervisor

would need to be written as:

SELECT Requisition.UniqueName, s.UniqueName


FROM Requisition
JOIN "User" AS u USING Requisition.Requester
JOIN "User" AS s USING u.Supervisor

An ON clause specifies a conditional expression for the JOIN. For example:

SELECT User.Name
FROM Requisition JOIN User ON (Requisition.Preparer = User)

The terms of the condition can be class names, table names, or field names. To use field names on both sides
of the condition, you would use the following syntax:

SELECT <select_elements> FROM A <join_type> B ON (A.anyField = B.anyField)

You must always join on compatible types. For example, in situations where there is a BaseID stored in a
string field, you can use the BaseID function to force the type compatibility. The following query shows how
to join to a POLineItem field, which is a BaseID:

SELECT Receipt.UniqueName, POLineItem.Quantity, ReceiptItem.NumberAccepted


FROM Receipt
JOIN ReceiptItem USING ReceiptItems
JOIN POLineItem ON BaseId(ReceiptItem.LineItemId) = POLineItem

42 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

Note: You cannot parenthesize join terms.

Examples SELECT emp.Name, mgr.Name


FROM User emp INNER JOIN User mgr USING Supervisor

SELECT emp.Name, mgr.Name


FROM User emp INNER JOIN User mgr ON emp.Supervisor = mgr

Grammar join_term_list ::=


join_term ( , join_term )*

join_term ::=
join_primary
| join_term [ join_type ] JOIN join_primary USING
field_reference
| join_term [ join_type ] JOIN join_primary ON
conditional_expression

join_primary ::=
class_reference

Java class AQLClassJoin extends AQLClassExpression

AQLClassJoin (AQLClassExpression leftClassExpr,


int joinOp,
AQLClassExpression rightClassExpr,
AQLFieldExpression leftJoinField);

AQLClassJoin (AQLClassExpression leftClassExpr,


int joinOp,
AQLClassExpression rightClassExpr,
AQLCondition onCondition);

Inner Joins
A join clause can specify a join type (inner or outer; left or right).

An inner join returns results only when the specified column exists in both tables. This is the most common
join. For example, this query:

SELECT "User".UniqueName, "Role".UniqueName FROM "User"


INNER JOIN "Role" USING Roles

returns only those User objects that have at least one associated role. It does not include users without roles,
or roles not associated with a user.

Note: Role and User are quoted because they are reserved words. For a list of reserved words, see “Reserved
Words” on page 67.

You can also write this query with dot notation:

SELECT "User".UniqueName, "User".Roles.UniqueName FROM "User"

The auto-join used to implement dot notation always uses an INNER join. To use any other kind of join, you
must use an explicit join type clause. For example, to specify a left outer join from Java code, you could set
Java options as follows:

Ariba Spend Management Query API Guide 43


Annotated Grammar Chapter 4 Query Language Details

options.setDefaultAutoJoinType(AQLClassExpression.OpJoinLeftOuter);

Queries The following queries are equivalent:

SELECT User.Name FROM Requisition, User


WHERE Requisition.Preparer = User

SELECT User.Name
FROM Requisition JOIN User ON (Requisition.Preparer = User)

SELECT User.Name FROM Requisition JOIN User USING Preparer

SELECT User.Name
FROM Requisition INNER JOIN User ON (Requisition.Preparer = User)

SELECT User.Name
FROM Requisition INNER JOIN User USING Preparer

Grammar join_type ::=


INNER
| LEFT [ OUTER ]
| RIGHT [ OUTER ]

Outer Joins
An outer join returns the same results as an inner join, and also includes all rows from either the first table,
or the second, or both. In the users/roles example, a left outer join includes all users, regardless of whether
they have roles, and a right outer join includes all roles, regardless of whether they are associated with a user.

For example, consider the following query:

SELECT "User".UniqueName, "Role".UniqueName


FROM "User"
LEFT OUTER JOIN "Role" USING Roles

This query always returns at least one row for each user, regardless of whether that user has a role. For users
who have 0 or 1 role this query returns one row. For users who have multiple roles, this query returns as
many rows as the number of roles.

The outer join between User and Role means that users who have 0 roles (column 1 is null) are also returned
in the query. That is, users who have no roles still have a row in the results. This is not true of an inner join.

Restrictions on left outer joins are as follows:


• The class on the right-hand side of a left outer join must either be a ClusterRoot or be an indirect
BaseObject. That is, there must be a table for that class.

For example, objects of type Money are embedded in a ClusterRoot, so there is no table created for Money.
You cannot write a query that uses Money as the right operand of a left outer join (such as LEFT OUTER
JOIN Money mon USING des.Price).

• A FROM clause can itself include a join statement. For example:


Select c
From Table1 LEFT OUTER JOIN Table2 ON Table1.SomeField

In this context, the join terms must be single tables. For example, this syntax causes an assert failed error:
Select c
From Table1,Table2 LEFT OUTER JOIN Table3 USING Table1.SomeField

44 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

But this syntax is valid:


Select c
From Table1 LEFT OUTER JOIN Table2 LEFT OUTER JOIN Table3
USING Table1.SomeField

Conditional Expressions
You use conditional expressions in WHERE clauses, to add constraints to your query. For example, a simple
condition is SELECT x, y FROM z WHERE x = 1 OR y = 1. In Java, the conditional expressions are subclasses
of AQLCondition. Ariba Query API conditionals are like those in SQL.

conditional_primary ::=
comparison_condition
| between_condition
| like_condition
| in_condition
| all_or_any_condition
| exists_condition
| test_for_null_condition
| function_condition
| ( conditional_expression )

Comparison Conditions
A comparison condition selects data using standard comparison operators.

Grammar comparison_condition ::=


scalar_expression comparison_operator scalar_expression

comparison_operator ::=
= | == | < | <= | > | >= | <> | !=

equality_operator ::=
= | == | <> | !=

Java AQLComparisonCondition extends AQLCondition

AQLComparisonCondition (AQLScalarExpression leftExpr,


int op,
AQLScalarExpression rightExpr);

static final int OpEqual = 4;


static final int OpNotEqual = 5;
static final int OpLess = 6;
static final int OpLessEqual = 7;
static final int OpGreater = 8;
static final int OpGreaterEqual = 9;

The Equal and NotEqual operators can be applied to operands of type BOOLEAN, NUMERIC, STRING, DATE, or
BASEID. The other comparison operators may only be applied to operands of type BOOLEAN, NUMERIC, STRING,
or DATE.

For all comparison operators, both operands must be of the same type.

Ariba Spend Management Query API Guide 45


Annotated Grammar Chapter 4 Query Language Details

Between Conditions
A between condition selects between two endpoints.

Example SELECT x.a FROM x WHERE x.b BETWEEN 10 AND 20

Grammar between_condition ::=


scalar_expression between_operator scalar_expression
AND scalar_expression

between_operator ::=
BETWEEN
| NOT BETWEEN

Java AQLBetweenCondition extends AQLCondition

AQLBetweenCondition (AQLScalarExpression leftExpr,


int op,
AQLScalarExpression fromExpr,
AQLScalarExpression toExpr);

static final int OpBetween = 10;


static final int OpNotBetween = 11;

The BETWEEN operator is allowed on operands of type BOOLEAN, NUMERIC, STRING, or DATE. All operands must be
of the same type. As in SQL, the BETWEEN operator is inclusive of the end points. For example, this query is
not valid, because the operands are not of like types:

SELECT Name from Course PARTITION pmarseille


WHERE FinalExamDate BETWEEN CurrentDate() - 90 AND CurrentDate()

The workaround is to rewrite the query, like this:

SELECT Name from Course PARTITION pmarseille


WHERE CurrentDate() - FinalExamDate BETWEEN 0 AND 90

Like Conditions
A like operator selects string data that matches a specified pattern. You can use the following wildcards in
the pattern:
_ matches any single character
% matches a sequence of zero or more characters.

46 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

If you need to include one of these wildcard characters as a literal, use an ESCAPE clause to define an escape
character, and then use that escape character in the pattern, as shown in the second example below. An
ESCAPE clause must be a single-character string literal.

Examples SELECT x.a FROM x WHERE x.s LIKE ‘a%’

SELECT x.a FROM x WHERE x.s LIKE ‘=_%’ ESCAPE ‘=’

(matches strings that begin with underscore; escapes the underscore)


Grammar like_condition ::=
scalar_expression like_operator scalar_expression
[ ESCAPE scalar_expression ]

like_operator ::=
LIKE
| NOT LIKE

Java AQLLikeCondition extends AQLCondition

AQLLikeCondition (AQLScalarExpression leftExpr,


int op,
AQLScalarExpression rightExpr,
AQLScalarExpression escapeExpr);

AQLLikeCondition (AQLScalarExpression leftExpr,


AQLScalarExpression rightExpr);

(from class AQLCondition)

static final int OpLike = 12;


static final int OpNotLike = 13;

The LIKE operator is case-insensitive. If you want to do a case-sensitive LIKE, you can use the Like function
instead, passing in TRUE for the case-sensitivity flag. (See “Function Calls as Terms” on page 58).

Ariba Spend Management Query API Guide 47


Annotated Grammar Chapter 4 Query Language Details

In Conditions
An in condition specifies data that matches the specified list.

Examples SELECT x.a FROM x WHERE x.b IN (SELECT y FROM z)

SELECT x.a FROM x WHERE x.b IN (10, 20, 30)

SELECT x.a FROM x WHERE 10 IN x.vector.c

Grammar in_condition ::=


scalar_expression in_operator ( class_expression )
| scalar_expression in_operator ( scalar_expression_list )
| scalar_expression in_operator field_reference

in_operator ::=
IN
| NOT IN

Java AQLInCondition extends AQLCondition

AQLInCondition (AQLScalarExpression leftExpr,


int op,
AQLClassExpression classExpr);

AQLInCondition (AQLScalarExpression leftExpr,


int op,
List scalarExpressionList);

AQLInCondition (AQLScalarExpression leftExpr,


int op,
AQLFieldExpression vectorField);

(from class AQLCondition)

static final int OpIn = 14;


static final int OpNotIn = 15;

The IN operator is allowed on operands of type BOOLEAN, NUMERIC, STRING, DATE, or BASEID. All operands
must be of the same type.

48 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

Any Conditions and All Conditions


An any or all condition uses the operators SOME, ANY, and ALL to specify the data to be selected. Note that, as
in ANSI SQL, SOME is equivalent to ANY.

Examples SELECT x.a FROM x WHERE x.b <> ALL (SELECT y FROM z)
SELECT x.a FROM x WHERE x.b = ANY (10, 20, 30)
SELECT x.a FROM x WHERE 10 = ANY x.vector.c

Grammar all_or_any_condition ::=


scalar_expression comparison_operator all_any_operator
( class_expression )
| scalar_expression equality_operator ( ANY | SOME )
( scalar_expression_list )
| scalar_expression comparison_operator all_any_operator
field_reference

all_any_operator ::=
ALL
| ANY
| SOME

Java AQLAllCondition extends AQLCondition


AQLAnyCondition extends AQLCondition

AQLAllCondition (AQLScalarExpression leftExpr,


int comparisonOp,
AQLClassExpression classExpr);

AQLAllCondition (AQLScalarExpression leftExpr,


int comparisonOp,
List scalarExpressionList);

AQLAllCondition (AQLScalarExpression leftExpr,


int comparisonOp,
AQLFieldExpression vectorField);

AQLAnyCondition (AQLScalarExpression leftExpr,


int comparisonOp,
AQLClassExpression classExpr);

AQLAnyCondition (AQLScalarExpression leftExpr,


int comparisonOp,
List scalarExpressionList);

AQLAnyCondition (AQLScalarExpression leftExpr,


int comparisonOp,
AQLFieldExpression vectorField);

Ariba Spend Management Query API Guide 49


Annotated Grammar Chapter 4 Query Language Details

Exists Conditions
An exists condition selects objects that exist in the database.

Example SELECT x.a FROM x


WHERE EXISTS (SELECT y FROM z WHERE z.b = x.b)

Grammar exists_condition ::=


EXISTS ( class_expression )

Java class AQLExistsCondition extends AQLCondition

AQLExistsCondition (ClassExpression classExpr);

(from class AQLCondition)

static final int OpExists = 19;

Test for Null Conditions


A test for null condition selects objects whose value is null. The operand can be any of the supported
types.

Example SELECT x.a FROM x WHERE x.b IS NULL

Grammar test_for_null_condition ::=


scalar_expression null_operator

null_operator ::=
IS [ NOT ] NULL

Java class AQLNullCondition extends AQLCondition

AQLNullCondition (int op,


AQLScalarExpression expr);

(from class AQLCondition)

static final int OpIsNull = 20;


static final int OpIsNotNull = 21;

In the case of BASEOBJECT, baseobject IS [NOT] NULL will be treated as BaseId(baseobject) IS [NOT] NULL.
Note that as in SQL:

expression IS NULL

is the way to test for NULL, not:

expression = NULL

which never evaluates to true, even if expression is null.

50 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

Function Conditions
A function condition makes a function call to a function that returns a Boolean. The value of the condition is
the return value of the function.

Example SELECT x.a FROM x WHERE BeginsWith(x.b, ‘a’)

Grammar function_condition ::=


scalar_function_expression

Combining Conditionals
You can combine conditional expressions with AND, OR, and NOT.

Example SELECT x, y FROM z WHERE x = 1 OR y = 1

Grammar conditional_expression ::=


conditional_term
| conditional_expression OR conditional_term

Java AQLOrCondition extends AQLCondition

AQLOrCondition (AQLCondition leftCondition,


AQLCondition rightCondition);

(from class AQLCondition)

static final int OpOr = 1;

Example SELECT x, y FROM z WHERE x = 1 AND y = 1

Grammar conditional_term ::=


conditional_factor
| conditional_term AND conditional_factor

Java AQLAndCondition extends AQLCondition

AQLAndCondition (AQLCondition leftCondition,


AQLCondition rightCondition);

(from class AQLCondition)

static final int OpAnd = 2;

Ariba Spend Management Query API Guide 51


Annotated Grammar Chapter 4 Query Language Details

Example SELECT x.a FROM x


WHERE NOT EXISTS (SELECT y.b FROM y WHERE y.c = x.c)

Grammar conditional_factor ::=


[ NOT ] conditional_primary

Java AQLNotCondition extends AQLCondition

AQLNotCondition (AQLCondition Condition);

(from class AQLCondition)

static final int OpNot = 3;

Scalar Expressions
A scalar expression is an expression that represents a single basic data type. Scalar expressions are used
throughout Ariba Query API, in SELECT clauses, WHERE clauses, and conditions. This section describes the
syntax of scalar expressions.

Scalar Expression Operations

Grammar scalar_expression_list ::=


scalar_expression ( , scalar_expression )*

scalar_expression ::=
bitwise_or_expression

Java AQLScalarExpression extends AQLCondition

AQLScalarExpression (String expressionText);

AQLStringLiteral extends AQLScalarExpression;

Bitwise Or Operator
A scalar expression can use the bitwise OR operator. The bitwise OR operator takes two parameters, both of
INTEGER type.

Example SELECT x.a FROM x WHERE (x.b | 4) <> 0

Grammar bitwise_or_expression ::=


bitwise_and_expression
| bitwise_or_expression | bitwise_and_expression

Java (from class AQLScalarExpression)

static final int OpBinaryBitOr = 1;

52 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

Bitwise And Operator


A scalar expression can use the bitwise AND operator. The bitwise AND operator takes two parameters, both of
INTEGER type.

Example SELECT x.a FROM x WHERE (x.b & 4) <> 0

Grammar bitwise_and_expression ::=


additive_expression
| bitwise_and_expression & additive_expression

Java (from class AQLScalarExpression)

static final int OpBinaryBitAnd = 2;

Addition and Subtraction Operators


A scalar expression can use addition, subtraction, and string addition (concatenation) operators.

Example SELECT x.a FROM x WHERE x.b + x.c – x.d > 100
SELECT ‘Name = ‘ || x.a FROM x WHERE x.b = 10

Grammar additive_expression ::=


scalar_term
| additive_expression additive_operator scalar_term

additive_operator ::=
+ | - | ||

Java (from class AQLScalarExpression)

static final int OpBinaryAdd = 3;


static final int OpBinarySubtract = 4;
static final int OpBinaryConcatenate = 5;

For + both operands must be NUMERIC.

For || both operands must be STRING.

For – both operands must be NUMERIC or both operands must be DATE. If you subtract two dates, the result is a
Double, representing the difference in days. For example, to return the number of PurchaseOrders submitted
in the last 30 days:

SELECT COUNT(*)
FROM PurchaseOrder
WHERE CurrentDate() - SubmitDate <= 30

Ariba Spend Management Query API Guide 53


Annotated Grammar Chapter 4 Query Language Details

Multiplicative Operator
A scalar expression can use standard multiplication and division operators.Both operands must be NUMERIC.

Example SELECT x.a FROM x WHERE (2 * x.a) / x.b < 1

Grammar multiplicative_operator ::=


* | /

Java (from class AQLScalarExpression)

static final int OpBinaryMultiply = 6;


static final int OpBinaryDivide = 7;

Unary Operators
A scalar expression can use the standard unary operator. The operand must be NUMERIC.

Example SELECT +x.a FROM x


SELECT –x.a FROM x WHERE x < 0

Grammar unary_operator ::=


+ | -

Java (from class AQLScalarExpression)

static final int OpUnaryPositive = 1;


static final int OpUnaryNegative = 2;

54 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

Scalar Expression Terms


This section describes the grammar for terms in scalar expressions.

Grammar scalar_term ::=


scalar_factor
| scalar_term multiplicative_operator scalar_factor

scalar_factor ::=
[ unary_operator ] scalar_primary

scalar_primary ::=
field_reference
| literal_or_parameter
| scalar_subquery
| case_expression
| ( scalar_expression )
| scalar_function_reference
| aggregate_function_reference

literal_or_parameter ::=
literal
| parameter

Java AQLUnaryExpression extends AQLScalarExpression

AQLUnaryExpression (int op,


AQLScalarExpression expression);

Literals as Terms

Ariba Spend Management Query API Guide 55


Annotated Grammar Chapter 4 Query Language Details

A term in the scalar expression can be a literal.

Grammar literal ::=


numeric_literal
| <string_literal>
| <date_literal>
| <baseid_literal>
| TRUE
| FALSE
| NULL

numeric_literal ::=
<floating_point_literal>
| <integer_literal>

Java class AQLStringLiteral extends AQLScalarExpression


AQLStringLiteral (String value);

class AQLDateLiteral extends AQLScalarExpression


AQLDateLiteral (Date value);

class AQLBooleanLiteral extends AQLScalarExpression


AQLBooleanLiteral (boolean value);

class AQLNullLiteral extends AQLScalarExpression


AQLNullLiteral ();

class AQLIntegerLiteral extends AQLScalarExpression


AQLIntegerLiteral (int value);

class AQLFloatingPointLiteral extends AQLScalarExpression


AQLFloatingPointLiteral (double value);

Parameters as Terms
Scalar expressions can include references to query parameters, specified either by name or by position. In a
given query, you must refer to parameters either by name or by position, but you can’t mix the two within a
query. For information on how to supply the parameters at runtime, see “Specifying Query Options” on
page 14.

The type of a parameter is optional, and is usually derived by context. If the type is not specified, and can’t
be determined from context, the query raises a validation error).

Example SELECT x.a FROM x WHERE x.b = :my_parameter


SELECT x.a FROM x WHERE x.b = :1

Grammar parameter ::=


: ( parameter_name | <integer_literal> )

Java class AQLParameter extends AQLScalarExpression


AQLParameter (String name);
AQLParameter (int position);

56 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

Subqueries as Terms
A WHERE clause can use a subquery, within the WHERE clause. The subquery class expression must result in a
single column from a single row. The type of a scalar subquery is the type of its single select list element,
which must be BOOLEAN, NUMERIC, STRING, DATE, or BASEID.

Note that scalar subquery are permitted only in a WHERE clause. They are not permitted in the select list.

Example SELECT x.a FROM x


WHERE x.c = (SELECT y FROM z WHERE z.b = x.b)

Grammar scalar_subquery ::=


( class_expression )

Java class AQLScalarSubquery extends AQLScalarExpression

AQLScalarSubquery (ClassExpression classExpr);

Case Expressions as Terms


A scalar term can be a case_expression, to express a SQL case statement. The case expression and all of the
WHEN expressions must be type compatible. The ELSE expression (if any) and all of the THEN expressions must
be type compatible. The control expression is evaluated, and then each WHEN clause is evaluated until one
evaluates to the same value as the control expression. The corresponding THEN expression is the result. If no
match is found and an ELSE expression is present, it is the result. If no match is found and no ELSE expression
is present, NULL is the result. A NULL WHEN expression does match a NULL control expression.

Example SELECT
CASE status
WHEN 1 THEN ‘Open’
WHEN 2 THEN ‘Closed’
ELSE ‘Unknown’
END
FROM x

Grammar case_expression ::=


CASE scalar_expression
( WHEN scalar_expression THEN scalar_expression )+
[ ELSE scalar_expression ]
END

Java class AQLCaseExpression extends AQLScalarExpression


AQLCaseExpression (AQLScalarExpression controlExpression,
List whenList,
List thenList,
AQLScalarExpression elseExpression);

Ariba Spend Management Query API Guide 57


Annotated Grammar Chapter 4 Query Language Details

Function Calls as Terms


A scalar expression can include a call to a built-in function.

Grammar scalar_function_reference ::=


builtin_function_name [ ( [ scalar_expression_list ] ) ]

Java class AQLFunctionCall extends AQLScalarExpression

AQLFunctionCall (String functionName,


List scalarExpressionList);

Aggregate Functions as Terms


A scalar expression can include an aggregate function as a term. An aggregate function is a function that
such as average or sum, which takes multiple values as input and returns a single value.

Examples SELECT COUNT(*) FROM x


SELECT COUNT(DISTINCT x.a) FROM x
SELECT SUM(x.a) FROM x
SELECT AVG(ALL x.a) FROM x

Grammar aggregate_function_reference ::=


Count ( * )
| aggregate_function_name ([ALL | DISTINCT] scalar_expression )

aggregate_function_name ::=
AVG | COUNT | MAX | MIN | Stdev | SUM | Variance

Java AQLFunctionCall (String name,


List parameterList);

AQLFunctionCall (AQLFieldExpression name,


List parameterList,
boolean isDistinct,
boolean includeNulls);

The functions AVG, STDEV, SUM, and VARIANCE take a single argument of a NUMERIC type. The functions MAX and
MIN take a single argument of type BOOLEAN, NUMERIC, STRING, or DATE. The COUNT function can take a single
argument of type BOOLEAN, NUMERIC, STRING, DATE, BASEID, or BASEOBJECT.

Other Statement Types


This section describes the other statement types supported by Ariba Query API: update, delete, and create.

The delete statement is only allowed on SQL tables, not classes, and there are restrictions on the update
statement. This section describes the limitations on each statement type.

Update Statements
An update statement changes rows in the database. You can perform an update either on a table or a class.
The only valid update statements are those that modify a single SQL table. If you write update statements
that reference classes, you must ensure that those update statements do not reference fields in more than one
table. For example:

58 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

// This example will NOT work


String queryString = "UPDATE ariba.procure.core.ReceiptNotificationPreferences rp
SET rp.OfWaitingApprovable = 0 ";

This statement mentions only one class, but the ReceiptNotificationPreferences derives from
ApprovableNotificationPreferences, which is a normalized class—that is, a class that isn’t stored in a single
table. This query results in the following error message:

"ariba.base.core.aql.AQLValidateException:
ariba.base.core.aql.AQLVisitorException: Class ariba.procure.core.ReceiptNotificationPreferences
cannot be UPDATEd because the DML Statement references more than one table".

Also, note that unlike transactionCommit(), the AQL Update does not clear the local session cache. Instead,
the caller is responsible for clearing the cache after an AQL Update is done. In this example, a call to
transactionCommit() is used to clear the session cache:

int numRows = -1;


try {
numRows = Base.getService().executeUpdate(aql, options);
}
catch (AQLException ex) {
String message = Fmt.S("Error while executing update: %s\n%s",
ex,
SystemUtil.stackTrace(ex));
}
Base.getSession().transactionCommit();
// Check results
root = Base.getSession().objectFromId(id);
If the local session cache is not cleared, the next objectFromId call could retrieve stale data.

Grammar update_statement ::=


UPDATE class_reference
SET update_set_list
[ WHERE conditional_expression ]

update_set_list ::=
update_set_element ( , update_set_element )*

update_set_element ::=
field_reference = scalar_expression

Java class AQLUpdate extends AQLStatement

AQLUpdate (AQLClassReference classRef,


List updateSetList,
AQLCondition where);

class AQLUpdateElement extends AQLNode

AQLUpdateElement (AQLFieldExpression field,


AQLScalarExpression expr);

Ariba Spend Management Query API Guide 59


Annotated Grammar Chapter 4 Query Language Details

Delete Statements
A delete statement deletes a record from a table. The only valid delete statements are those that modify a
single SQL table. You must delete from a table, and not from a class. These restrictions are enforced at
statement validation time.

Grammar delete_statement ::=


DELETE FROM class_reference
[ WHERE conditional_expression ]

Java class AQLDelete extends AQLStatement

Create Statements
You use a create statement to execute a SQL CREATE VIEW statement. The SQL CREATE VIEW statement
defines a view, which is a logical table based on one or more tables or views. A view does not contain any
data itself.

The create statement gives the view a name and includes a select statement that provides the columns and
rows of the view. You can then access the new view either from the Query API or directly from SQL, using
external tools.

Query String CREATE VIEW UserRoles (UserName, RoleName) AS


SELECT "User".Name, r.Name
FROM "User".Roles r

Grammar create_statement ::=


create_view_statement

create_view_statement ::=
CREATE VIEW field_expression [ ( field_reference_list ) ]
AS class_expression

Java class AQLCreateView extends AQLStatement

AQLCreateView (AQLFieldExpression viewName,


List fieldList,
AQLClassExpression classExpression);

The field_reference_list is an optional list that defines the names of the columns. In the example above,
the columns are UserName and RoleName. If you omit the column names, the default is to use the names
deduced from the SELECT statement. Those column names must be unique. It is a validation error to omit
field_reference_list if the default names are not unique. (In the example above, the default column names
would both be Name, so the explicit column names are required.)

Built-in Functions
This section describes the functions that Ariba Query API provides as built-in functions.

Example SELECT Lower(Name) FROM x


WHERE Substring(x.code, 1, 3) = ‘abc’

Grammar builtin_function_name ::=

60 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

Abs Acos Asin Atan


Atan2 BaseId BeginsWith Ceiling
ClassCode ClassName ClassVariant COALESCE
CONTAINS Cos CurrentDate CurrentTime
CurrentTimestamp DATE DAY EndsWith
Exp Length LIKE Ln
Log10 LOWER Ltrim Mod
MONTH OBJECT POSITION Power
ROUND Rtrim Sign Sin
Sqrt SUBSTRING Tan Translation
Trunc UPPER YEAR

Notes:
• Function names are not keywords (except the ones that are SQL92 reserved words) and are not
case-sensitive.
• Ariba Query API recognizes the SQL standard functions CURRENT DATE, CURRENT TIME, and CURRENT
TIMESTAMP as synonyms for CurrentDate, CurrentTime, and CurrentTimestamp, respectively. For SQL
compatibility, these three functions (only) may appear with no argument list.

String Functions
This section describes string functions.

boolean BeginsWith (String s1, String s2 [, boolean caseSense ]);

Returns true if s1 begins with s2. The optional boolean caseSense determines if the comparison is
case-sensitive:
If caseSense is FALSE (the default), BeginsWith is shorthand for
LOWER(s1) LIKE LOWER(s2 || ‘%’)

If caseSense is TRUE, BeginsWith is shorthand for


s1 LIKE (s2 || ‘%’)

boolean CONTAINS (String s1, String s2 [, boolean caseSense ]);

Returns true if s1 contains s2. The optional boolean caseSense determines if the comparison is
case-sensitive:
If caseSense is FALSE (the default), CONTAINS is shorthand for
LOWER(s1) LIKE LOWER(‘%’ || s2 || ‘%’)

If caseSense is TRUE, CONTAINS is shorthand for


s1 LIKE ‘%’ || s2 || ‘%’

boolean EndsWith (String s1, String s2 [, boolean caseSense ]);

Returns true if s1 ends with s2. The optional boolean caseSense determines if the comparison is
case-sensitive:
If caseSense is FALSE (the default), EndsWith is shorthand for
LOWER(s1) LIKE LOWER(‘%’ || s2)

Ariba Spend Management Query API Guide 61


Annotated Grammar Chapter 4 Query Language Details

If caseSense is TRUE, EndsWith is shorthand for


s1 LIKE (‘%’ || s2)

int Length (String s);

Returns the length of the string in characters.

boolean LIKE (String s1, String s2 [, boolean caseSensitive ]);

Behaves as the LIKE function with no escape option, but with the option to be case-sensitive. If the case
parameter is omitted, the default is case-insensitive

String LOWER (String s);

Returns s lowercased.

String Ltrim (String s);

Returns s with any leading blanks removed.

int POSITION (String s1, String s2 [, int n]);

Returns the starting position of s1 in s2, starting at character n. n defaults to 1. Returns 0 if s1 is not in s2.

String Rtrim (String s);

Returns s with any trailing blanks removed.

String SUBSTRING (String s, int m [, int n]);

Returns the portion of s starting at m that is n characters long. If n is omitted, returns the suffix of s
starting at m.

String Translation(String s1, String s2);

Returns the translation of s1 in the specified language if it exists, otherwise returns the default language
string. s1 is a multi-lingual string field, and s2 is a literal quoted string that is the unique name of a
language object (which is case-sensitive).

String UPPER (String s);

Returns s uppercased.

BLOB Search Functions


Ariba Query API supports functionality to search fields of type BLOB (Binary Large Object). The following
functions are supported:

boolean CONTAINS (ariba.util.core.blobField searchField,


String searchPattern);

Returns true if the specified searchPattern is found within the binary data stored in the BLOB field;
returns false otherwise. For example:
SELECT ObjectWithLob
FROM test.ariba.base.core.ObjectWithLob
WHERE CONTAINS(SomeBlobField.BlobField, 'mySearchPattern')

To use this function, note the following restrictions:

62 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

• The first argument must be of type ariba.util.core.Blob. In metadata XML, fields are declared of type
ariba.base.core.Blob, which in turn contains a field (always called BlobField), of type
ariba.util.core.Blob. To search a BLOB, you must use dot notation to specify the BLOB field:
YourClass.YourBlobField.BlobField.

• BLOB search relies on content search support in the underlying database. You are responsible for
enabling content search support on your database. If you have not enabled appropriate database support,
the CONTAINS function throws a SQL exception.

Numeric Functions
This section lists the built-in functions related to numeric operations.

double Abs (Numeric n);

Returns the absolute value of n.

double Acos (Numeric n);

Returns the angle in radians whose cosine is n.

double Asin (Numeric n);

Returns the angle in radians whose sine is n.

double Atan (Numeric n);

Returns the angle in radians whose tangent is n.

double Atan2 (Numeric n1, Numeric n2);

Returns the angle in radians whose tangent is between n1 and n2.

long Ceiling (Numeric n);

Returns the smallest integer >= n.

double Cos (Numeric n);

Returns the cosine of the given angle (n in radians).

double Exp (Numeric n);

Returns the inverse natural logarithm of n.

double Ln (Numeric n);

Returns the natural logarithm of n.

double Log10 (Numeric n);

Returns the base 10 logarithm of n.

long Mod (Long i1, Long i2);

Returns i1 modulo i2.

double Power (Numeric x, Numeric y);

Returns x to the y power.

Ariba Spend Management Query API Guide 63


Annotated Grammar Chapter 4 Query Language Details

double ROUND (double n [, int m]);

Return n rounded to m places to the right of the decimal (or to the left of the decimal if m is negative). m
defaults to 0.

int Sign (Numeric n);

Returns the sign of n as 1 (+), 0 (0), or -1 (-).

double Sin (Numeric n);

Returns the sine of the given angle (n in radians).

double Sqrt (Numeric n);

Returns the square root of n.

double Tan (Numeric n);

Returns the tangent of the given angle (n in radians),

double Trunc (Numeric n [, int m]);

Returns n rounded to m places to the right of the decimal or (to the left of the decimal if m is negative). m
defaults to 0.

Date Functions
This section lists the built-in functions related to dates. Also note that you can subtract dates, as described in
“Addition and Subtraction Operators” on page 53.

Date CalendarDate (String dateString);

Constructs a literal representing a calendar date. The literal is always interpreted as a date in GMT. (To
include a timezone, use the Date function instead.) For example:
SELECT OrderDate FROM Requisition WHERE
OrderDate >= CalendarDate('2001-10-22 00:00:00')

The format of date literals is described in “Date literals” on page 31.

Date Date (String dateString);

Constructs a date literal, including a required timezone. For example:


SELECT xField FROM yClass WHERE xField = Date('2002-08-09 PDT')00')

The format of date literals is described in “Date literals” on page 31.

Date CurrentDate ();

Returns the current date, in GMT. For example:

SELECT xField FROM yClass WHERE xField = CurrentDate()

Date CurrentTime ();

Returns the current time. For example:


SELECT CurrentTime() FROM yClass;

Date CurrentTimestamp ();

Returns the current date and time. For example:

64 Ariba Spend Management Query API Guide


Chapter 4 Query Language Details Annotated Grammar

SELECT CurrentTimestamp() FROM yClass;

int DAY (Date d);

Returns the day of the month (a value in the range 1-31) for the date d. For example:
SELECT xField FROM yClass WHERE DAY(xDate) = 1

Note that the DAY function always returns values in GMT, and does not correct for the timezone in which
the server is located.

int MONTH (Date d);

Returns the month of the year (a value in the range 1-12) for the date d. For example:
SELECT xField FROM yClass WHERE MONTH(xDate) = 12

Note that the MONTH function always returns values in GMT, and does not correct for the timezone in which
the server is located.

int YEAR (Date d);

Returns the (four digit) year for the date d. For example:
SELECT xField FROM yClass WHERE Year(xDate) = 1999

Note that the YEAR function always returns values in GMT, and does not correct for the timezone in which
the server is located.

Class Functions
String ClassCode (String class [, String variant] );
String ClassCode (BaseId id);
String ClassCode (BaseObject object);

Evaluates to the internal class code. If variant is omitted, Ariba Query API chooses a default. If the class
is partitioned, the default is the variant for the partition, as specified in the AQLOptions object. If the class
is not partitioned, the default is Plain.

String ClassName (String code);


String ClassName (BaseId id);
String ClassName (BaseObject object);

Evaluates to the class name for the argument.

String ClassVariant (String code);


String ClassVariant (BaseId id);
String ClassVariant (BaseObject object);

Evaluates to the variant name for the argument.

Conversion Functions
The functions in this section convert between BaseIDs, BaseObjects, and the literal representations of those
objects.

BaseId BaseId (BaseObject);

Returns the BaseId of a BaseObject.

Ariba Spend Management Query API Guide 65


Known Limitations Chapter 4 Query Language Details

BaseId BaseId (BaseId);

Does nothing. Defined only for type safety, so that the conversion of a BaseID to a BaseID is defined as a
valid conversion.

BaseId BaseId (String idString);

Returns the BaseID corresponding to a string literal representing a BaseID. This is the equivalent of a
BaseID ‘literal’.

BaseObject OBJECT (BaseId);

Returns the object corresponding to the BaseID. This function has been deprecated and support will be
removed in a future release.

BaseObject OBJECT (BaseObject);

No-op. Defined only for type safety, so that the conversion of a BaseObject to a BaseObject is defined as
a valid conversion. This function has been deprecated and support will be removed in a future release.

BaseObject OBJECT (String idString);

Returns the object corresponding to a string literal representation of a BaseId. This function has been
deprecated and support will be removed in a future release.

Miscellaneous Functions
AnyType COALESCE (AnyType Expression1, AnyType Expression2)

Provides the same functionality as the Oracle NVL function or the MSSQLServer ISNULL function. That
is, it evaluates to:
if (Expression1 IS NOT NULL)
then Expression1
else Expression2

The expressions may be of any type, but both expressions must be of the same time.

Known Limitations
The following are known limitations of Ariba Query API:
• There is no function or operator to do field-by-field comparisons on objects.
• GROUP BY and HAVING clauses are not allowed on queries that result in internally generated UNIONs.
• Java method invocation is not supported, (except for callback option).
• The USING clause in an explicit JOIN can only be used against classes.
• The maximum number of parameters in a statement is 254.

66 Ariba Spend Management Query API Guide


Appendix A
Reserved Words

This appendix lists all reserved words in Ariba Query API, both those that are currently used by Ariba Query
API and those that are reserved for future use. In the list below, the words in bold are the keywords currently
used by Ariba Query API. The other words are reserved for future use.

ABSOLUTE ACCESS ACTION ACTIVE


ADA ADD AFTER ALIAS
ALL ALLOCATE ALTER AND
ANSI ANY APPEND ARCHIVE
ARE ARRAY AS ASC
ASSERT ASSERTION AT ATTACH
ATTRIBUTE AUDIT AUTHORIZATION AVG
BACKUP BAG BASE BECOME
BEFORE BEGIN BETWEEN BIT
BIT_LENGTH BLOCK BODY BOOLEAN
BOTH BOTTOM BREAK BROWSE
BUFFER BUFFERED BY BYTE
CACHE CALL CANCEL CARDINALITY
CASCADE CASCADED CASE CAST
CATALOG CHANGE CHAR CHARACTER
CHAR_LENGTH CHARACTER_LENGTH CHECK CHECKPOINT
CLASS CLOSE CLUSTER CLUSTERED
COALESCE COBOL COLLATE COLLATION
COLUMN COMMENT COMMIT COMMITTED
COMPARE COMPILE COMPUTE CONFIRM
CONNECT CONNECTION CONST CONSTRAINT
CONSTRAINTS CONTAINS CONTENT CONTENTS
CONTEXT CONTINUE CONVERT COPY
CORRESPONDING COUNT CREATE CROSS
CURRENT CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP
CURRENT_USER CURSOR CYCLE CYCLIC
DATABASE DATE DATETIME DAY
DBA DEALLOCATE DEBUG DEC
DECIMAL DECLARE DECODE DEFAULT
DEFERRABLE DEFERRED DEFINE DENORMALIZED
DENY DELETE DERIVE DERIVED
DESC DESCRIBE DESCRIPTOR DETACH
DIAGNOSTICS DICTIONARY DIRECT DIRTY
DISABLE DISABLED DISCONNECT DISTINCT
DISTRIBUTED DO DONT DOMAIN

Ariba Spend Management Query API Guide 67


Appendix A Reserved Words

DOUBLE DOWN DROP DUMP


EACH ELEMENT ELIF ELSE
ENABLE ENABLED END END-EXEC
ENTITY ENUM ENUMERATE ENUMERATED
ERROR ESCAPE EVENT EVENTS
EVERY EXCEPT EXCEPTION EXCEPTIONS
EXCLUDE EXCLUSIVE EXEC EXECUTE
EXISTS EXIT EXPLAIN EXPRESSION
EXTEND EXTENSION EXTENT EXTERNAL
EXTERNALLY EXTRACT FALSE FETCH
FIELD FILE FILLFACTOR FILTER
FILTERING FIRST FLATTEN FLOAT
FLUSH FOR FORCE FOREIGN
FORMAT FORTRAN FOUND FRACTION
FRAGMENT FROM FULL FUNC
FUNCTION GET GLOBAL GO
GOTO GRANT GRAPH GROUP
HAVING HELP HIGH HINT
HOLD HOLDLOCK HOUR ID
IDENTIFIED IDENTIFY IDENTITY IF
IMMEDIATE IMPLEMENTOR IN INACTIVE
INCLUDE INCLUDING INCREMENT INDEX
INDEXES INDICATOR INDIRECT INIT
INITIAL INITIALLY INNER INOUT
INPUT INSENSITIVE INSERT INSTANCE
INT INTEGER INTERFACE INTERSECT
INTERVAL INTO INVERSE IS
ISOLATION JAVA JAVADOC JOIN
KEY KEYS KILL LANGUAGE
LAST LEADING LEFT LET
LEVEL LIKE LINK LIST
LISTTOSET LOAD LOCAL LOCK
LOG LONG LOWER MANUAL
MANY MAP MATCH MAX
METHOD MIN MINUS MINUTE
MODE MODIFY MODULE MONTH
MORE NAMES NATIONAL NATURAL
NCHAR NEW NEWS NEXT
NIL NO NOCHECK NOWAIT
NONCLUSTERED NON NONE NORMAL
NORMALIZED NOT NULL NULLABLE
NULLIF NUMBER NUMERIC OBJECT
OBJECTS OCTET OCTET_LENGTH OF
OFF OFFLINE OLD ON
ONCE ONE ONEWAY ONLINE

68 Ariba Spend Management Query API Guide


Appendix A Reserved Words

ONLY OPEN OPTIMAL OPTIMIZE


OPTION OR ORDER OUT
OUTER OUTPUT OWN OVER
OVERLAPS OVERRIDE OVERRIDES PACKAGE
PAD PARALLEL PARAMETER PARTIAL
PARTITION PASCAL PATH PERCENT
PERMISSION PLAN PLI POSITION
PRECISION PREPARE PRESERVE PRIMARY
PRIOR PRINT PRIVATE PRIVILIGE
PRIVILEGES PROC PROCEDURE PROFILE
PROPERTY PROTECTED PUBLIC QUIT
RAISES RAW READ READONLY
REAL REFERENCES REFERENCING RELATIONSHIP
RELATIVE RENAME REPEATABLE REPLACE
REPLICATE REPLICATION RESOURCE RESTRICT
RESTRICTED RESTORE RETURN REUSE
REVOKE RIGHT ROLE ROLES
ROLLBACK ROUND ROW ROWS
RULE SAVE SAVEPOINT SCALE
SCHEMA SCROLL SEARCH SECOND
SECTION SEGMENT SELECT SENSITIVE
SEQUENCE SERIALIZABLE SESSION SESSION_USER
SET SHARE SHARED SHUTDOWN
SIGNATURE SIGNED SIZE SMALLINT
SOME SORT SPACE SQL
SQLCA SQLCODE SQLERROR SQLSTATE
SQLWARNING STABILITY START STATISTICS
STDEV STOP STRING STRUCT
SUBCLASS SUBSTRING SUM SUPER
SUPERCLASS SWITCH SYNONYM SYSDATE
SYSTEM SYSTEM_USER TABLE TABLES
TEMP TEMPORARY TEXT THEN
THREAD THROWS TIME TIMEOUT
TIMESTAMP TIMEZONE_HOUR TIMEZONE_MINUTE TO
TOP TRACE TRACING TRAILING
TRAN TRANSACTION TRANSLATE TRANSLATION
TRIM TRIGGER TRIGGERS TRUE
TRUNCATE TYPE TYPE_NAME TYPEDEF
UID UNCOMMITTED UNDER UNION
UNIQUE UNIT UNITS UNKNOWN
UNLOCK UNSIGNED UNTIL UP
UPDATE UPPER USAGE USE
USER USING VALIDATE VALIDATOR
VALUE VALUES VARCHAR VARIANCE
VARIANT VARYING VECTOR VIEW

Ariba Spend Management Query API Guide 69


Appendix A Reserved Words

VIOLATION VIOLATIONS VOID WAIT


WHEN WHENEVER WHERE WHILE
WITH WITHOUT WORD WORDS
WORK WRITE XOR YEAR
ZERO ZONE

70 Ariba Spend Management Query API Guide


Appendix B
Command Reference

This appendix provides reference information on the syntax of command-line tools described in this
document.

aribaquery
You use aribaquery to run database queries from the command line.

Syntax
To run aribquery, type the following at a command prompt in the bin directory:

aribaquery -username username -password password -host hostname -port port

The command line returns with an AQL> prompt. At that prompt, you can enter Ariba Query API queries. For
example:

AQL> SELECT * from Address;

To submit a query after entering it, you must either terminate the command with a semicolon, or type go on a
separate line. For example:

AQL> SELECT * from Address


AQL> go

Options
The following command line options are available for the aribaquery command. Note that all options are
case-sensitive.

-host hostname

Use this option to specify a specific host name. The host must be explicitly specified; do not use
localhost.

-port port

This option is required. Use it to specify the RPC port used for client connections. In the default
multiserver configuration, the RPC port for the logical node Node1 is 8052; for logical node Node2, the port
is 8056. You can override the default port with any valid port number.

-username username

Use this option to log in as a specific user. The -username flag is almost always used with the -password
option.

Ariba Spend Management Query API Guide 71


aribaquery Appendix B Command Reference

-password password

Use this option to specify a password for use with -username.

-stdinPassword

Use this option to read a password from standard input. You can use it as an alternative to -password when
security is a concern.
For example, the syntax for -password includes the password immediately on the line:
aribaquery -username vlo -password myPassword
AQL>

But for -stdinPassword, the password is on a separate line, instead of immediately after the
-stdinPassword option:

aribaquery -username vlo -stdinPassword


myPassword
AQL>

The advantage of -stdinPassword is that the password is protected from commands like ‘ps’ which would
display the process running without the password.

-Ssl

This option enables secure (encrypted) RPCs when using Secure Socket Layer (SSL). This option is the
default. To run without SSL, use the -noSsl option.

-noSsl

This option disables secure (encrypted) RPCs when using Secure Sockets Layer (SSL). If you are not
using SSL in your configuration, you must specify this option to connect successfully.

-domain domain

Use this option to specify an NT domain to use for authentication. This option is relevant only when you
are using NT Domain Authentication.

-passwordAdapter passwordAdapter

Use this option to specify the password adapter to be used for authentication. This option is required only
if there are multiple password adapters available for the specified user.

-usecache

Use this option to specify that the query results cache should be used. The default is not to use the cache.

-noUsecache

Use this option to turn off -usecache.

-classupdate

Use this option to specify that queries can make updates to classes.

-noClassupdate

Use this option to turn off -classupdate.

-unionlimit unionlimit

Use this option to specify the maximum number of unions allowed in a generated query.

72 Ariba Spend Management Query API Guide


Appendix B Command Reference aribaquery

-echo

Use this option to cause the commands you type to be echoed on the screen. The default is -noecho.

-noEcho

Use this option to disable -echo.

Ariba Spend Management Query API Guide 73


aribaquery Appendix B Command Reference

74 Ariba Spend Management Query API Guide


Index

A CalendarDate function 31, 64


active objects, queries on 39 callbacks, on query results 15
actual parameters, in AQLOptions 15 case-sensitivity
addition operation 53 aribaquery command 9
aggregate functions 58 function names 30
aliases, using in queries 38 identifiers 30
AQL classes class code functions 65
AQLCondition class 13 class names
AQLError class 17, 18 in queries 36, 37
AQLNameTable class 25 ClassCode function 65
AQLOptions 14, 15 cluster roots
AQLQuery 13 fetching 18
AQLResultCallback 15 COALESCE function 66
AQLResultCollection class 16 command line
AQLResultField class 17, 18 aribaquery command 71
AQLStatement 13 queries from 9
aql log category 10 comparison conditions 45
aribaquery conditional expressions 45
SSL option 72 any or all 49
SSL options 9 in queries 13
aribaquery command 9, 72 join clauses 42
case-sensitivity 9 constraints
options 71 on queries 13
query cache 72 CONTAINS function, for BLOB field 62
syntax 71 conversion functions 65
arithmetic operations 53 create statement 60
auto-joins 24 CREATE VIEW statement 60

B D
base objects data types 32
fetching 18, 33 dates
baseID literals 31 creating from literals 31
between conditions 46 date format 31
bitwise operations Date function 31
bitwise and 53 expressing as literals 31
bitwise or 52 functions on dates 64
BLOB fields subtracting dates 53
queries on 35 debugging
searching 62 debugging long queries 10
built-in functions 58 log categories 10
delete statements 60
restrictions on 60
C derived fields, queries on 24
division operator 54
cache
dot notation
caching nametable queries 25
in queries 22, 37
query cache 25
OR queries 22
query cache size 26

Ariba Spend Management Query API Guide 75


Index

E excluding from queries 39


errors filtering for 19
converting to strings 17 inner joins 43
parsing from results 16 Inspector 9
escape characters, for wildcards 47 starting 9
example integer literals 30
of left outer join 44
examples
J
aribaquery tool 9
auto-join 24 join clauses 41
basic Query API example 11 dot notation and 22, 37
clearing query cache 59 left outer joins 44
conditions from parsed string 13
date queries 31
dot notation in queries 22 K
errors in results 17 keywords 28
filter by partition 19 quoting 30
inactive object query 19
join clauses 42
partition queries 41 L
queries from Inspector 9 left outer join
results processing 17 example 44
select statements 34 restrictions on 44
update statements 16, 58 like conditions 46
vector query 24 like operator
vector subscript 39 escaping wildcards 47
executeQuery method 14, 15 limitations of Ariba Query API 66
executeUpdate method 14 literals 30
executing queries 14 baseID literals 31
exists conditions 50 date literals 31
expressions, function calls for 58 floating point literals 30
in query strings 13
integer literals 30
F string literals 31
fetching objects 16 locale
field aliases in queries 20 MLS fields 20
floating point literals 30 specifying in query 20
functions logging 10
case-sensitivity in function calls 30 log categories 10
class code functions 65 queryperf log category 10
coalesce function 66 LongString 34
date functions 64
expressions using functions 58
numeric operations 63 M
string operations 61 metadata, fetching from queries 18
Translation 62 multi-lingual strings
type conversion functions 65 accessing from queries 20
in queries 38
multiplication operator 54
H
host option, aribaquery command 71
N
name scope 38
I named parameters in queries 13
identifiers 30 nametables
case-sensitivity 30 caching queries 25
inactive objects custom nametables 25

76 Ariba Spend Management Query API Guide


Index

noPersist fields query defaults 7


querying on 24 query options 14
noQuery attribute 24 query strings and objects 12
normalized tables restricting by partition 40
accessing from queries 21 restrictions on field queries 24
noSchema attribute, on classes 23 specifying locale 20
numeric operations specifying partition 19
functions 63 string query 12
validating 14, 15
query cache 25, 72
O cache size 26
objects, fetching 16 sizing 26
operators 29 query object
OR queries, dot notation and 22 converting to string 12
order by clause 36 query options
outer joins 44 cache 25
restrictions on 44 query string
converting to object 12
converting to query object 12
P including literals 13
parameters QueryCacheSize parameter 26
in scalar expressions 56 QueryExecutionThresholdMilliseconds parameter 10
named parameters in queries 13 QueryGenerationThresholdSQLBytes parameter 10
query parameters 15 queryperf log category 10
parseQuery method 12 quoting
partition reserved words 22, 30
filtering by partition 7
restricting queries by partition 40
specifying in query 14, 19 R
performance, query cache and 25 reserved words 67
port option, aribaquery 71 quoting 22
punctuation 29 results
purged objects accessing data type 18
queries on 19 accessing error messages 16
callbacks on 15
ordering 36
Q parsing 17
queries processing results 16
active/inactive objects and 39 result sets 16
adding constraints 13
BLOB fields 35
building from Java 13 S
by class name 36 scalar expressions 52
by subclass 36 scoping 38
by table name 36 query scope 38
command line 9 select statements
debugging long queries 10 selecting BaseObjects 33
derived fields and 23 wildcards 33
examples of 24 setUseCache method 25
executing 14, 15 SSL, with aribaquery command 9, 72
field aliases 38 string functions 61
including subclasses 41 string literals 31
locale in queries 14 string queries 12
multi-lingual strings and 38 subclass modifier 41
name scope 38 subtraction operator 53
order of query results 36 symbols, terminal symbols 28
partition in queries 14

Ariba Spend Management Query API Guide 77


Index

T
terminal symbols 28
toString method 12
Translation function 62
type, result type 18

U
unary operator 54
update statements 16
restrictions on 16, 58
write access requirements 16
User, as reserved word 22
USING clause, in join 42

V
validating queries 14
vectors 21
accessing from queries 21
auto-join 23
dot notation 23
query example 24
subscripting vectors 38
views
creating SQL views 60

W
wildcard 47
wildcards
escape characters 47
select statements 33
write access, in update operations 16

78 Ariba Spend Management Query API Guide


Index

Ariba Spend Management Query API Guide 79


ARIBA, INC.
807 11th Avenue
Sunnyvale, CA 94089 USA
Telephone: 650.390.1000
Fax: 650.390.1100
www.ariba.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy