]> git.evergreen-ils.org Git - working/Evergreen.git/blob - 2.0/development/json.xml
Made three small grammar fixes inside the EG 1.6 serveradministration.xml file
[working/Evergreen.git] / 2.0 / development / json.xml
1 <?xml version="1.0" encoding="utf-8"?>\r
2 <chapter xml:id="JSON_Queries" xmlns="http://docbook.org/ns/docbook" version="5.0" xml:lang="EN"\r
3     xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xlink="http://www.w3.org/1999/xlink">\r
4         <info>\r
5                 <title>JSON Queries</title>\r
6         <indexterm><primary>JSON</primary></indexterm>\r
7         </info>\r
8         <para>The json_query facility provides a way for client applications to query the database over the network. Instead of constructing its own SQL, the application encodes a query in the \r
9         form of a JSON string and passes it to the json_query service. Then the json_query service parses the JSON, constructs and executes the corresponding SQL, and returns the results to \r
10         the client application.</para>\r
11         <para>This arrangement enables the json_query service to act as a gatekeeper, protecting the database from potentially damaging SQL commands. In particular, the generated SQL is \r
12         confined to SELECT statements, which will not change the contents of the database.</para>\r
13 \r
14         <para>In addition, the json_query service sometimes uses its knowledge of the database structure to supply column names and join conditions so that the client application doesn't \r
15         have to.</para>\r
16 \r
17         <para>Nevertheless, the need to encode a query in a JSON string adds complications, because the client needs to know how to build the right JSON. JSON queries are also somewhat \r
18         limiting -- they can't do all of the things that you can do with raw SQL.</para>\r
19         <simplesect>\r
20                 <title>The IDL</title>\r
21 \r
22                 <para>A JSON query does not refer to tables and columns. Instead, it refers to classes and fields, which the IDL maps to the corresponding database entities.</para>\r
23 \r
24                 <para>The IDL (Interface Definition Language) is an XML file, typically <filename>/openils/conf/fm_IDL.xml</filename>. It maps each class to a table, view, or subquery, and \r
25                 each field to a column. It also includes information about foreign key relationships.</para>\r
26 \r
27                 <para>(The IDL also defines virtual classes and virtual fields, which don't correspond to database entities. We won't discuss them here, because json_query ignores them.)</para>\r
28 \r
29                 <para>When it first starts up, json_query loads a relevant subset of the IDL into memory. Thereafter, it consults its copy of the IDL whenever it needs to know about the database \r
30                 structure. It uses the IDL to validate the JSON queries, and to translate classes and fields to the corresponding tables and columns. In some cases it uses the IDL to supply information \r
31                 that the queries don't provide.\r
32                 Definitions</para>\r
33 \r
34                 <para>You should also be familiar with JSON. However it is worth defining a couple of terms that have other meanings in other contexts:</para>\r
35 \r
36                 <itemizedlist>\r
37                         <listitem><para>An "object" is a JSON object, i.e. a comma-separated list of name:value pairs, enclosed in curly braces, like this:</para>\r
38                                 <screen>{ "a":"frobozz", "b":24, "c":null }</screen>\r
39                         </listitem>\r
40                         <listitem><para>An "array" is a JSON array, i.e. a comma-separated list of values, enclosed in square brackets, like this:</para>\r
41                                 <screen>[ "Goober", 629, null, false, "glub" ]</screen>\r
42                         </listitem>     \r
43                 </itemizedlist>                                 \r
44         </simplesect>\r
45         <simplesect>\r
46                 <title>The Examples</title>\r
47                 <para>The test_json_query utility generated the SQL for all of the sample queries in this tutorial. Newlines and indentation were then inserted manually for readability.</para>\r
48                 <para>All examples involve the actor.org_unit table, sometimes in combination with a few related tables. The queries themselves are designed to illustrate the syntax, not \r
49                 to do anything useful at the application level. For example, it's not meaningful to take the square root of an org_unit id, except to illustrate how to code a function call. \r
50                 The examples are like department store mannequins -- they have no brains, they're only for display.</para>\r
51                 <para>The simplest kind of query defines nothing but a FROM clause. For example:</para>\r
52                 <programlisting>\r
53                 {\r
54                         "from":"aou"\r
55                 }\r
56                 </programlisting>\r
57                 <para>In this minimal example we select from only one table. Later we will see how to join multiple tables.</para>\r
58                 <para>Since we don't supply a WHERE clause, json_query constructs a default WHERE clause for us, including all the available columns. The resulting SQL looks like this:</para>\r
59 <programlisting language="sql">\r
60 SELECT\r
61     "aou".billing_address AS "billing_address",\r
62     "aou".holds_address   AS "holds_address",\r
63     "aou".id              AS "id",\r
64     "aou".ill_address     AS "ill_address",\r
65     "aou".mailing_address AS "mailing_address",\r
66     "aou".name            AS "name",\r
67     "aou".ou_type         AS "ou_type",\r
68     "aou".parent_ou       AS "parent_ou",\r
69     "aou".shortname       AS "shortname",\r
70     "aou".email           AS "email",\r
71     "aou".phone           AS "phone",\r
72     "aou".opac_visible    AS "opac_visible"\r
73 FROM\r
74         actor.org_unit        AS "aou" ;        \r
75 </programlisting>\r
76          </simplesect>\r
77         <simplesect>\r
78                 <title>Default SELECT Clauses</title>\r
79                 <indexterm><primary>JSON</primary><secondary>SELECT clauses</secondary></indexterm>\r
80                 <para>The default SELECT clause includes every column that the IDL defines it as a non-virtual field for the class in question. If a column is present in the database but \r
81                 not defined in the IDL, json_query doesn't know about it. In the case of the example shown above, all the columns are defined in the IDL, so they all show up in the default \r
82                 SELECT clause.</para>\r
83                 <para>If the FROM clause joins two or more tables, the default SELECT clause includes columns only from the core table, not from any of the joined tables.</para>\r
84                 <para>The default SELECT clause has almost the same effect as "SELECT *", but not exactly. If you were to "SELECT * from actor.org_unit_type in psql, the output would \r
85                 include all the same columns as in the example above, but not in the same order. A default SELECT clause includes the columns in the order in which the IDL defines them, \r
86                 which may be different from the order in which the database defines them.</para>        \r
87                 <para>In practice, the sequencing of columns in the SELECT clause is not significant. The result set is returned to the client program in the form of a data structure, which \r
88                 the client program can navigate however it chooses.</para>\r
89         </simplesect>   \r
90         <simplesect>\r
91                 <title>Other Lessons</title>\r
92                 <para>There are other ways to get a default SELECT clause. However, default SELECT clauses are a distraction at this point, because most of the time you'll specify your \r
93                 own SELECT clause explicitly, as we will discuss later.</para>\r
94                 <para>Let's consider some more important aspects of this simple example -- more important because they apply to more complex queries as well.</para>\r
95                 <itemizedlist>\r
96                         <listitem>\r
97                                 <para> The entire JSON query is an object. In this simple case the object includes only one entry, for the FROM clause. Typically you'll also have entries \r
98                                 for the SELECT clause and the WHERE clause, and possibly for HAVING, ORDER BY, LIMIT, or OFFSET clauses. There is no separate entry for a GROUP BY clause, which you \r
99                                 can specify by other means.</para>      \r
100                         </listitem>\r
101                         <listitem>\r
102                                 <para>Although all the other entries are optional, you must include an entry for the FROM clause. You cannot, for example, do a SELECT USER the way \r
103                                 you can in psql.</para> \r
104                         </listitem>\r
105                         <listitem>\r
106                                 <para>Every column is qualified by an alias for the table. This alias is always the class name for the table, as defined in the IDL.</para>     \r
107                         </listitem>\r
108                         <listitem>\r
109                                 <para>Every column is aliased with the column name. There is a way to choose a different column alias (not shown here).</para>  \r
110                         </listitem>     \r
111                 </itemizedlist>\r
112         </simplesect>\r
113         <simplesect>\r
114                 <title>The SELECT Clause</title>\r
115                 <para>The following variation also produces a default SELECT clause:</para>\r
116 <programlisting>\r
117 {\r
118         "from":"aou",\r
119         "select": {\r
120         "aou":"*"\r
121         }\r
122 }\r
123 </programlisting>\r
124                 <para>...and so does this one:</para>\r
125 <programlisting>\r
126 {\r
127         "select": {\r
128         "aou":null\r
129         },\r
130         "from":"aou"\r
131 }\r
132 </programlisting>\r
133                 <para>While this syntax may not be terribly useful, it does illustrate the minimal structure of a SELECT clause in a JSON query: an entry in the outermost JSON object, \r
134                 with a key of <quote>select</quote>. The value associated with this key is another JSON object, whose keys are class names.</para>\r
135                 <para>(These two examples also illustrate another point: unlike SQL, a JSON query doesn't care whether the FROM clause or the SELECT clause comes first.)</para>\r
136                 <para>Usually you don't want the default SELECT clause. Here's how to select only some of the columns:</para>\r
137 <programlisting>\r
138 {\r
139         "from":"aou",\r
140         "select": {\r
141         "aou":[ "id", "name" ]\r
142          }\r
143 }\r
144 </programlisting>\r
145                 <para>The value associated with the class name is an array of column names. If you select columns from multiple tables (not shown here), you'll need a separate entry for each table, \r
146                 and a separate column list for each entry.</para>\r
147                 <para>The previous example results in the following SQL:</para>\r
148 <programlisting>\r
149 SELECT\r
150         "aou".id       AS "id",\r
151         "aou".name     AS "name"\r
152 FROM\r
153         actor.org_unit AS "aou" ;\r
154 </programlisting>\r
155         </simplesect>\r
156         <simplesect>\r
157                 <title>Fancier SELECT Clauses</title>\r
158                 <para>The previous example featured an array of column names. More generally, it featured an array of field specifications, and one kind of field specification is a column name. \r
159                 The other kind is a JSON object, with some combination of the following keys:</para>\r
160                 <itemizedlist>\r
161                         <listitem>\r
162                                 <para><quote>column</quote> -- the column name (required).</para>       \r
163                         </listitem>\r
164                         <listitem>\r
165                                 <para><quote>alias</quote> -- used to define a column alias, which otherwise defaults to the column name.</para>        \r
166                         </listitem>\r
167                         <listitem>\r
168                                 <para><quote>aggregate</quote> -- takes a value of true or false. Don't worry about this one yet. It concerns the use of GROUP BY clauses, which we will examine \r
169                                 later.</para>   \r
170                         </listitem>\r
171                         <listitem>\r
172                                 <para><quote>transform</quote> -- the name of an SQL function to be called.</para>      \r
173                         </listitem>\r
174                                 <listitem>\r
175                                 <para><quote>result_field</quote> -- used with "transform"; specifies an output column of a function that returns multiple columns at a time.</para>    \r
176                         </listitem>\r
177                         <listitem>\r
178                                 <para><quote>params</quote> -- used with "transform"; provides a list of parameters for the function. They may be strings, numbers, or nulls.</para>    \r
179                         </listitem>     \r
180                 </itemizedlist> \r
181                 <para>This example assigns a different column alias:</para>\r
182 <programlisting>\r
183 {\r
184         "from":"aou",\r
185         "select": {\r
186                 "aou": [\r
187                         "id",\r
188                         { "column":"name", "alias":"org_name" }\r
189                 ]\r
190         }\r
191 }\r
192 \r
193 SELECT\r
194         "aou".id AS "id",\r
195         "aou".name AS "org_name"\r
196 FROM\r
197         actor.org_unit AS "aou" ;\r
198 </programlisting>\r
199                 <para>In this case, changing the column alias doesn't accomplish much. But if we were joining to the actor.org_unit_type table, which also has a "name" column, we could \r
200                 use different aliases to distinguish them.</para>\r
201                 <para>The following example uses a function to raise a column to upper case:</para>\r
202 <programlisting>\r
203 {\r
204         "from":"aou",\r
205         "select": {\r
206                 "aou": [\r
207                         "id",\r
208                         { "column":"name", "transform":"upper" }\r
209                 ]\r
210         }\r
211 }\r
212                 \r
213 SELECT\r
214         "aou".id           AS "id",\r
215         upper("aou".name ) AS "name"\r
216 FROM\r
217         actor.org_unit     AS "aou" ;\r
218 </programlisting>\r
219                 <para>Here we take a substring of the name, using the <emphasis role="italics">params</emphasis> element to pass parameters:</para>\r
220                 <programlisting>\r
221                 {\r
222                         "from":"aou",\r
223                         "select": {\r
224                                 "aou": [\r
225                                         "id", {\r
226                                                 "column":"name",\r
227                                                 "transform":"substr",\r
228                                                 "params":[ 3, 5 ]\r
229                                         }\r
230                                 ]\r
231                         }\r
232                 }\r
233                                 \r
234                 SELECT\r
235                         "aou".id AS "id",\r
236                         substr("aou".name,'3','5' ) AS "name"\r
237                 FROM\r
238                         actor.org_unit AS "aou" ;\r
239                 </programlisting>\r
240                 <para>The parameters specified with <emphasis role="italics">params</emphasis> are inserted after the applicable column (<emphasis role="italics">name</emphasis> in this case), \r
241                 which is always the first parameter. They are always passed as strings, i.e. enclosed in quotes, even if the JSON expresses them as numbers. PostgreSQL will ordinarily \r
242                 coerce them to the right type. However if the function name is overloaded to accept different types, PostgreSQL may invoke a function other than the one intended.</para>\r
243                 <para>Finally we call a fictitious function "frobozz" that returns multiple columns, where we want only one of them:</para>\r
244 <programlisting>\r
245 {\r
246         "from":"aou",\r
247         "select": {\r
248                 "aou": [\r
249                         "id", {\r
250                                 "column":"name",\r
251                                 "transform":"frobozz",\r
252                                 "result_field":"zamzam"\r
253                         }\r
254                 ]\r
255         }\r
256 }\r
257                 \r
258 SELECT\r
259         "aou".id                        AS "id",\r
260         (frobozz("aou".name ))."zamzam" AS "name"\r
261 FROM\r
262         actor.org_unit                  AS "aou" ;\r
263 </programlisting>\r
264                 <para>The <emphasis role="italics">frobozz</emphasis> function doesn't actually exist, but json_query doesn't know that. The query won't fail until json_query tries to execute it in \r
265                 the database.</para>\r
266         </simplesect>\r
267         <simplesect>\r
268                 <title>Things You Can't Do</title>\r
269                 <para>You can do some things in a SELECT clause with raw SQL (with psql, for example) that you can't do with a JSON query. Some of them matter and some of them don't.</para>\r
270                 <para>When you do a JOIN, you can't arrange the selected columns in any arbitrary sequence, because all of the columns from a given table must be grouped together. \r
271                 This limitation doesn't matter. The results are returned in the form of a data structure, which the client program can navigate however it likes.</para>\r
272                 <para>You can't select an arbitrary expression, such as "percentage / 100" or "last_name || ', ' || first_name". Most of the time this limitation doesn't matter either, because \r
273                 the client program can do these kinds of manipulations for itself. However, function calls may be a problem. You can't nest them, and you can't pass more than one column value \r
274                 to them (and it has to be the first parameter).</para>  \r
275                 <para>You can't use a CASE expression. Instead, the client application can do the equivalent branching for itself.</para>\r
276                 <para>You can't select a subquery. In raw SQL you can do something like the following:</para>\r
277 <programlisting>\r
278 SELECT\r
279         id,\r
280         name,\r
281         (\r
282                 SELECT name\r
283                 FROM actor.org_unit_type AS aout\r
284                 WHERE aout.id = aou.ou_type\r
285         ) AS type_name\r
286 FROM\r
287         actor.org_unit AS aou;\r
288 </programlisting>\r
289                 <para>This contrived example is not very realistic. Normally you would use a JOIN in this case, and that's what you should do in a JSON query. Other cases may not be so \r
290                 easy to solve.</para>\r
291         </simplesect>\r
292         <simplesect>\r
293                 <title>The WHERE Clause</title>\r
294                 <para>Most queries need a WHERE clause, as in this simple example:</para>\r
295 <programlisting>\r
296 {\r
297         "from":"aou",\r
298         "select": { "aou":[ "id", "name" ] },\r
299         "where": {\r
300                 "parent_ou":"3"\r
301         }\r
302 }\r
303 </programlisting>\r
304                 <para>Like the SELECT clause, the WHERE clause gets its own entry in the top-level object of a JSON query. The key is <quote>where</quote>, and the associated value is either \r
305                 an object (as shown here) or an array (to be discussed a bit later). Each entry in the object is a separate condition.</para>\r
306                 <para>In this case, we use a special shortcut for expressing an equality condition. The column name is on the left of the colon, and the value to which we are equating it is on \r
307                 the right.</para>\r
308                 <para>Here's the resulting SQL:</para>\r
309 <programlisting>\r
310 SELECT\r
311         "aou".id       AS "id",\r
312         "aou".name     AS "name"\r
313 FROM\r
314         actor.org_unit AS "aou"\r
315 WHERE\r
316         "aou".parent_ou = 3;\r
317 </programlisting>\r
318                 <para>Like the SELECT clause, the generated WHERE clause qualifies each column name with the alias of the relevant table.</para>\r
319                 <para>If you want to compare a column to NULL, put <quote>null</quote> (without quotation marks) to the right of the colon instead of a literal value. The \r
320                 resulting SQL will include <quote>IS NULL</quote> instead of an equals sign.</para>\r
321         </simplesect>\r
322         <simplesect>\r
323                 <title>Other Kinds of Comparisons</title>\r
324                 <para>Here's the same query (which generates the same SQL) without the special shortcut:</para>\r
325 <programlisting>\r
326 {\r
327         "from":"aou",\r
328         "select": { "aou":[ "id", "name" ] },\r
329         "where": {\r
330                 "parent_ou":{ "=":3 }\r
331         }\r
332 }\r
333 </programlisting>\r
334                 <para>We still have an entry whose key is the column name, but this time the associated value is another JSON object. It must contain exactly one entry, \r
335                 with the comparison operator on the left of the colon, and the value to be compared on the right.</para>\r
336                 <para>The same syntax works for other kinds of comparison operators. For example:</para>\r
337 <programlisting>\r
338 {\r
339         "from":"aou",\r
340         "select": { "aou":[ "id", "name" ] },\r
341         "where": {\r
342                 "parent_ou":{ ">":3 }\r
343         }\r
344 }\r
345 </programlisting>\r
346                 <para>...turns into:</para>\r
347 <programlisting>\r
348 SELECT\r
349         "aou".id       AS "id",\r
350         "aou".name     AS "name"\r
351 FROM\r
352         actor.org_unit AS "aou"\r
353 WHERE\r
354         "aou".parent_ou > 3 ;\r
355 </programlisting>\r
356                 <para>The condition '<quote>=</quote>:null' turns into IS NULL. Any other operator used with <quote>null</quote> turns into IS NOT NULL.</para>\r
357                 <para>You can use most of the comparison operators recognized by PostgreSQL:</para>\r
358                 <literallayout> \r
359                 =    &lt;&gt;   !=\r
360                 &lt;    &gt;    &lt;=   &gt;=\r
361                 ~    ~*   !~   !~*\r
362                 like      ilike\r
363                 similar to\r
364                 </literallayout>        \r
365                 <para>The only ones you can't use are <quote>is distinct from</quote> and <quote>is not distinct from</quote>.</para>           \r
366         </simplesect>\r
367         <simplesect>\r
368                 <title>Custom Comparisons</title>\r
369                 <para>Here's a dirty little secret: json_query doesn't really pay much attention to the operator you supply. It merely checks to make sure that the operator doesn't contain \r
370                 any semicolons or white space, in order to prevent certain kinds of SQL injection. It also allows "similar to" as a special exception.</para>\r
371                 <para>As a result, you can slip an operator of your own devising into the SQL, so long as it doesn't contain any semicolons or white space, and doesn't create invalid syntax. \r
372                 Here's a contrived and rather silly example:</para>\r
373 <programlisting>\r
374 {\r
375         "from":"aou",\r
376         "select": { "aou":[ "id", "name" ] },\r
377         "where": {\r
378                 "parent_ou":{ "&lt;2+":3 }\r
379         }\r
380 }\r
381 </programlisting>\r
382                 <para>...which results in the following SQL:</para>\r
383 <programlisting>\r
384 SELECT\r
385         "aou".id       AS "id",\r
386         "aou".name     AS "name"\r
387 FROM\r
388         actor.org_unit AS "aou"\r
389 WHERE\r
390         "aou".parent_ou &lt;2+ 3;\r
391 </programlisting>\r
392                 <para>It's hard to come up with a realistic case where this hack would be useful, but it could happen.</para>\r
393         </simplesect>\r
394         <simplesect>\r
395                 <title>Comparing One Column to Another</title>\r
396                 <para>Here's how to put another column on the right hand side of a comparison:</para>\r
397 <programlisting>\r
398 {\r
399         "from":"aou",\r
400         "select": { "aou":[ "id", "name" ] },\r
401         "where": {\r
402                 "id": { "&gt;": { "+aou":"parent_ou" } }\r
403         }\r
404 };\r
405 </programlisting>\r
406                 <para>This syntax is similar to the previous examples, except that instead of comparing to a literal value, we compare to an object. This object has only a single entry, \r
407                 whose key is a table alias preceded by a leading plus sign. The associated value is the name of the column.</para>\r
408                 <para>Here's the resulting SQL:</para>\r
409 <programlisting>\r
410 SELECT\r
411         "aou".id AS "id",\r
412         "aou".name AS "name"\r
413 FROM\r
414         actor.org_unit AS "aou"\r
415 WHERE\r
416 (\r
417         "aou".id &gt; (  "aou".parent_ou  )\r
418 );\r
419 </programlisting>\r
420                 <para>The table alias must correspond to the appropriate table. Since json_query doesn't validate the choice of alias, it won't detect an invalid alias until it tries to \r
421                 execute the query. In this simple example there's only one table to choose from. The choice of alias is more important in a subquery or join.</para>\r
422                 <para>The leading plus sign, combined with a table alias, can be used in other situations to designate the table to which a column belongs. We shall defer a discussion of \r
423                 this usage to the section on joins.</para>\r
424         </simplesect>           \r
425         <simplesect>\r
426                 <title>Testing Boolean Columns</title>\r
427                 <para>In SQL, there are several ways to test a boolean column such as actor.org_unit.opac_visible. The most obvious way is to compare it to true or false:</para>\r
428 <programlisting>\r
429 SELECT\r
430         id\r
431 FROM\r
432         actor.org_unit\r
433 WHERE\r
434         opac_visible = true;\r
435 </programlisting>\r
436                 <para>In a JSON query this approach doesn't work. If you try it, the "= true" test will turn into IS NULL. Don't do that. Instead, use a leading plus sign, as described in \r
437                 the preceding section, to treat the boolean column as a stand-alone condition:</para>\r
438 <programlisting>\r
439 {\r
440         "from":"aou",\r
441         "select": { "aou":[ "id" ] },\r
442         "where": {\r
443                 "+aou":"opac_visible"\r
444         }\r
445 }\r
446 </programlisting>\r
447                 <para>Result:</para>\r
448 <programlisting>\r
449 SELECT\r
450         "aou".id AS "id"\r
451 FROM\r
452         actor.org_unit AS "aou"\r
453 WHERE\r
454         "aou".opac_visible ;\r
455 </programlisting>\r
456                 <para>If you need to test for falsity, then write a test for truth and negate it with the "-not" operator. We will discuss the "-not" operator later, but here's a preview:</para>\r
457 <programlisting>\r
458 {\r
459         "from":"aou",\r
460         "select": { "aou":[ "id" ] },\r
461         "where": {\r
462                 "-not": {\r
463                         "+aou":"opac_visible"\r
464                 }\r
465         }\r
466 }                       \r
467 \r
468 SELECT\r
469         "aou".id AS "id"\r
470 FROM\r
471         actor.org_unit AS "aou"\r
472 WHERE\r
473         NOT (  "aou".opac_visible  );           \r
474 </programlisting>\r
475                 <para>You can also compare a boolean column directly to a more complex condition:</para>\r
476 <programlisting>\r
477 {\r
478         "from":"aou",\r
479         "select": { "aou":[ "id" ] },\r
480         "where": {\r
481                 "opac_visible": {\r
482                 "=": { "parent_ou":{ "&gt;":3 } }\r
483                 }\r
484          }\r
485 }\r
486 </programlisting>\r
487                 <para>Here we compare a boolean column, not to a literal value, but to a boolean expression. The resulting SQL looks a little goofy, but it works:</para>\r
488 <programlisting>\r
489 SELECT\r
490         "aou".id AS "id"\r
491 FROM\r
492         actor.org_unit AS "aou"\r
493 WHERE\r
494         (\r
495                 "aou".opac_visible = ( "aou".parent_ou &gt; 3 )\r
496         );\r
497 </programlisting>\r
498                 <para>In this case we compare the boolean column to a single simple condition. However you can include additional complications -- multiple conditions, IN lists, \r
499                 BETWEEN clauses, and other features as described below.</para>\r
500         </simplesect>\r
501         <simplesect>\r
502                 <title>Multiple Conditions</title>\r
503                 <para>If you need multiple conditions, just add them to the "where" object, separated by commas:</para>\r
504 <programlisting>\r
505 {\r
506         "from":"aou",\r
507         "select": { "aou":[ "id", "name" ] },\r
508         "where": {\r
509                 "parent_ou":{ "&gt;":3 },\r
510                 "id":{ "&lt;&gt;":7 }\r
511         }\r
512 }\r
513 </programlisting>\r
514                 <para>The generated SQL connects the conditions with AND:</para>\r
515 <programlisting>\r
516 SELECT\r
517         "aou".id       AS "id",\r
518         "aou".name     AS "name"\r
519 FROM\r
520         actor.org_unit AS "aou"\r
521 WHERE\r
522         "aou".parent_ou g 3\r
523         AND "aou".id &lt;&gt; 7;\r
524 </programlisting>\r
525                 <para>Later we will see how to use OR instead of AND.</para>\r
526         </simplesect>\r
527         <simplesect>\r
528                 <title>Using Arrays</title>\r
529                 <para>Here's a puzzler. Suppose you need two conditions for the same column. How do you code them in the same WHERE clause? For example, suppose you want something like this:</para>\r
530 <programlisting>\r
531 SELECT\r
532         id,\r
533         name\r
534 FROM\r
535         actor.org_unit\r
536 WHERE\r
537         parent_ou &gt; 3\r
538         AND parent_ou &lt;&gt; 7;\r
539 </programlisting>\r
540                 <para>You might try a WHERE clause like this:</para>\r
541 <programlisting>\r
542 "where": {\r
543         "parent_ou":{ "&gt;":3 },\r
544         "parent_ou":{ "&lt;&gt;":7 }\r
545  }\r
546 </programlisting>\r
547                 <para>Nope. Won't work. According to JSON rules, two entries in the same object can't have the same key.</para>\r
548                 <para>After slapping yourself in the forehead, you try something a little smarter:</para>\r
549 <programlisting>\r
550 "where": {\r
551         "parent_ou": {\r
552                 "&gt;":3,\r
553                 "&lt;&gt;":7\r
554         }\r
555 }\r
556 </programlisting>\r
557                 <para>Nice try, but that doesn't work either. Maybe it ought to work -- at least it's legal JSON -- but, no.</para>\r
558                 <para>Here's what works:</para>\r
559 <programlisting>\r
560 {\r
561         "from":"aou",\r
562         "select": { "aou":[ "id", "name" ] },\r
563         "where": [\r
564                 { "parent_ou":{ "&gt;":3 } },\r
565                 { "parent_ou":{ "&lt;>":7 } }\r
566         ]\r
567 }\r
568 </programlisting>\r
569                 <para>We wrapped the two conditions into two separate JSON objects, and then wrapped those objects together into a JSON array. The resulting SQL looks like this:</para>\r
570 <programlisting>\r
571 SELECT\r
572         "aou".id       AS "id",\r
573         "aou".name     AS "name\r
574 FROM\r
575         actor.org_unit AS "aou"\r
576 WHERE\r
577         ( "aou".parent_ou &gt; 3 )\r
578 AND\r
579         ( "aou".parent_ou &lt;&gt; 7 );\r
580 </programlisting>\r
581                 <para>That's not quite what we were hoping for, because the extra parentheses are so ugly. But they're harmless. This will do.</para>\r
582                 <para>If you're in the mood, you can use arrays to as many parentheses as you like, even if there is only one condition inside:</para>\r
583 <programlisting>\r
584 {\r
585         "from":"aou",\r
586         "select": { "aou":[ "id", "name" ] },\r
587         "where":\r
588         [[[[[[\r
589                 {\r
590                         "parent_ou":{ "&gt;":3 }\r
591                  },\r
592         ]]]]]]\r
593 }       \r
594 </programlisting>\r
595                 <para>...yields:</para>\r
596 <programlisting>\r
597 SELECT\r
598         "aou".id       AS "id",\r
599         "aou".name     AS "name"\r
600 FROM\r
601         actor.org_unit AS "aou"\r
602 WHERE\r
603         ( ( ( ( ( ( "aou".parent_ou &gt; 3 ) ) ) ) ) );\r
604 </programlisting>\r
605         </simplesect>\r
606         <simplesect>\r
607                 <title>How to OR</title>\r
608                 <para>By default, json_query combines conditions with AND. When you need OR, here's how to do it:</para>                \r
609 <programlisting>\r
610 {\r
611         "from":"aou",\r
612         "select": { "aou":[ "id", "name" ] },\r
613         "where": {\r
614                 "-or": {\r
615                         "id":2,\r
616                         "parent_ou":3\r
617                 }\r
618         }\r
619 }\r
620 </programlisting>\r
621                 <para>We use <quote>-or</quote> as the key, with the conditions to be ORed in an associated object. The leading minus sign is there to make sure that the operator isn't confused with a \r
622                 column name. Later we'll see some other operators with leading minus signs. In a couple of spots we even use plus signs.</para>\r
623                 <para>Here are the results from the above example:</para>\r
624 <programlisting>\r
625 SELECT\r
626         "aou".id AS "id",\r
627         "aou".name AS "name"\r
628 FROM\r
629         actor.org_unit AS "aou"\r
630 WHERE\r
631         (\r
632                 "aou".id = 2\r
633                 OR "aou".parent_ou = 3\r
634         );\r
635 </programlisting>\r
636                 <para>The conditions paired with <quote>-or</quote> are linked by OR and enclosed in parentheses.</para>\r
637                 <para>Here's how to do the same thing using an array, except that it produces an extra layer of parentheses:</para>\r
638 <programlisting>\r
639 {\r
640     "from":"aou",\r
641     "select": { "aou":[ "id", "name" ] },\r
642     "where": {\r
643         "-or": [\r
644             { "id":2 },\r
645             { "parent_ou":3 }\r
646         ]\r
647     }\r
648 }\r
649 SELECT\r
650     "aou".id AS "id",\r
651     "aou".name AS "name"\r
652 FROM\r
653     actor.org_unit AS "aou"\r
654 WHERE\r
655     (\r
656         ( "aou".id = 2 )\r
657         OR ( "aou".parent_ou = 3 )\r
658     );\r
659 </programlisting>\r
660                 <para>It's possible, though not very useful, to have only a single condition subject to the <quote>-or</quote> operator. In that case, the condition appears by itself, since there's nothing \r
661                 to OR it to. This trick is another way to add an extraneous layer of parentheses.</para>\r
662         </simplesect>\r
663         <simplesect>\r
664                 <title>Another way to AND</title>\r
665                 <para>You can also use the <quote>-and</quote> operator. It works just like <quote>-or</quote>, except that it combines conditions with AND instead of OR. Since AND is the default, we don't usually \r
666                 need a separate operator for it, but it's available.</para>\r
667                 <para>In rare cases, nothing else will do -- you can't include two conditions in the same list because of the duplicate key problem, but you can't combine them with \r
668                 arrays either. In particular, you might need to combine them within an expression that you're comparing to a boolean column (see the subsection above on Testing Boolean Columns).</para>\r
669         </simplesect>\r
670         <simplesect>\r
671                 <title>Negation with NOT</title>\r
672                 <para>The <quote>-not</quote> operator negates a condition or set of conditions. For example:</para>\r
673 <programlisting>\r
674 {\r
675         "from":"aou",\r
676         "select": { "aou":[ "id", "name" ] },\r
677         "where": {\r
678                 "-not": {\r
679                         "id":{ "&gt;":2 },\r
680                         "parent_ou":3\r
681                 }\r
682         }\r
683 }\r
684                 \r
685 SELECT\r
686         "aou".id AS "id",\r
687         "aou".name AS "name"\r
688 FROM\r
689         actor.org_unit AS "aou"\r
690 WHERE\r
691         NOT\r
692         (\r
693                 "aou".id &gt; 2\r
694                 AND "aou".parent_ou = 3\r
695         );\r
696 </programlisting>\r
697                 <para>In this example we merely negate a combination of two comparisons. However the condition to be negated may be as complicated as it needs to be. Anything that can be \r
698                 subject to <quote>where</quote> can be subject to <quote>-not</quote>.</para>\r
699                 <para>In most cases you can achieve the same result by other means. However the <quote>-not</quote> operator is the only way to represent NOT BETWEEN \r
700                 (to be discussed later).</para> \r
701         </simplesect>\r
702         <simplesect>\r
703                 <title>EXISTS with Subqueries</title>\r
704                 <para>Two other operators carry a leading minus sign: <quote>-exists</quote> and its negation <quote>-not-exists</quote>. These operators apply to subqueries, which have the \r
705                 same format as a full query. For example:</para>\r
706 <programlisting>        \r
707 {\r
708         "from":"aou",\r
709         "select": { "aou":[ "id", "name" ] },\r
710         "where": {\r
711                 "-exists": {\r
712                         "from":"asv",\r
713                         "select":{ "asv":[ "id" ] },\r
714                         "where": {\r
715                                 "owner":7\r
716                         }\r
717                 }\r
718         }\r
719 }\r
720                 \r
721 SELECT\r
722         "aou".id AS "id",\r
723         "aou".name AS "name"\r
724 FROM\r
725         actor.org_unit AS "aou"\r
726 WHERE\r
727 EXISTS\r
728         (\r
729         SELECT "asv".id AS "id"\r
730         FROM action.survey AS "asv"\r
731         WHERE "asv".owner = 7\r
732         );\r
733 </programlisting>\r
734                 <para>This kind of subquery is of limited use, because its WHERE clause doesn't have anything to do with the main query. It just shuts down the main query altogether \r
735                 if it isn't satisfied.</para>\r
736                 <para>More typical is a correlated subquery, whose WHERE clause refers to a row from the main query. For example:</para>\r
737 <programlisting>        \r
738 {\r
739         "from":"aou",\r
740         "select": { "aou":[ "id", "name" ] },\r
741         "where": {\r
742                 "-exists": {\r
743                         "from":"asv",\r
744                         "select":{ "asv":[ "id" ] },\r
745                         "where": {\r
746                                 "owner":{ "=":{ "+aou":"id" }}\r
747                         }\r
748                 }\r
749          }\r
750 }       \r
751 </programlisting>\r
752                 <para>Note the use of <quote>+aou</quote> to qualify the id column in the inner WHERE clause.</para>\r
753 <programlisting>        \r
754 SELECT\r
755         "aou".id AS "id",\r
756         "aou".name AS "name"\r
757 FROM\r
758         actor.org_unit AS "aou"\r
759 WHERE\r
760         EXISTS\r
761         (\r
762                 SELECT  "asv".id AS "id"\r
763                 FROM action.survey AS "asv"\r
764                 WHERE ("asv".owner = (  "aou".id  ))\r
765         );\r
766 </programlisting>\r
767                 <para>This latter example illustrates the syntax, but in practice, it would probably be more natural to use an IN clause with a subquery (to be discussed later).</para>\r
768         </simplesect>\r
769         <simplesect>\r
770                 <title>BETWEEN Clauses</title>\r
771                 <para>Here's how to express a BETWEEN clause:</para>\r
772 <programlisting>        \r
773 {\r
774         "from":"aou",\r
775         "select": { "aou":[ "id" ] },\r
776         "where": {\r
777                 "parent_ou": { "between":[ 3, 7 ] }\r
778         }\r
779 }\r
780 </programlisting>\r
781                 <para>The value associated with the column name is an object with a single entry, whose key is "between". The corresponding value is an array with exactly two values, defining the \r
782                 range to be tested.</para>\r
783                 <para>The range bounds must be either numbers or string literals. Although SQL allows them to be null, a null doesn't make sense in this context, because a null never matches \r
784                 anything. Consequently json_query doesn't allow them.</para>\r
785                 <para>The resulting SQL is just what you would expect:</para>\r
786 <programlisting>        \r
787 SELECT\r
788         "aou".id AS "id"\r
789 FROM\r
790         actor.org_unit AS "aou"\r
791 WHERE\r
792         parent_ou BETWEEN '3' AND '7';\r
793 </programlisting>\r
794         </simplesect>\r
795         <simplesect>\r
796                 <title>IN and NOT IN Lists</title>\r
797                 <para>There are two ways to code an IN list. One way is simply to include the list of values in an array:</para>\r
798 <programlisting>        \r
799 {\r
800         "from":"aou",\r
801         "select": { "aou":[ "id", "name" ] },\r
802         "where": {\r
803                 "parent_ou": [ 3, 5, 7 ]\r
804         }\r
805 }\r
806 </programlisting>\r
807                 <para>As with a BETWEEN clause, the values in the array must be numbers or string literals. Nulls aren't allowed. Here's the resulting SQL, which again is just what \r
808                 you would expect:</para>\r
809 <programlisting>        \r
810 SELECT\r
811         "aou".id AS "id",\r
812         "aou".name AS "name"\r
813 FROM\r
814         actor.org_unit AS "aou"\r
815 WHERE\r
816         "aou".parent_ou IN (3, 5, 7);\r
817 </programlisting>\r
818                 <para>The other way is similar to the syntax shown above for a BETWEEN clause, except that the array may include any non-zero number of values:</para>\r
819 <programlisting>        \r
820 {\r
821         "from":"aou",\r
822         "select": { "aou":[ "id", "name" ] },\r
823         "where": {\r
824                 "parent_ou": { "in": [ 3, 5, 7 ] }\r
825         }\r
826 }\r
827 </programlisting>\r
828                 <para>This version results in the same SQL as the first one.</para>\r
829                 <para>For a NOT IN list, you can use the latter format, using the <quote>not in</quote> operator instead of <quote>in</quote>. Alternatively, you can use either format together with \r
830                 the <quote>-not</quote> operator.</para>        \r
831         </simplesect>\r
832         <simplesect>\r
833                 <title>IN and NOT IN Clauses with Subqueries</title>\r
834                 <para>For an IN clause with a subquery, the syntax is similar to the second of the two formats for an IN list (see the previous subsection). The "in" or "not in" operator \r
835                 is paired, not with an array of values, but with an object representing the subquery. For example:</para>\r
836 <programlisting>        \r
837 {\r
838         "from":"aou",\r
839         "select": { "aou":[ "id", "name" ] },\r
840         "where": {\r
841                 "id": {\r
842                         "in": {\r
843                                 "from":"asv",\r
844                                 "select":{ "asv":[ "owner" ] },\r
845                                 "where":{ "name":"Voter Registration" }\r
846                                 }\r
847                         }\r
848         }\r
849 }\r
850 </programlisting>\r
851                 <para>The results:</para>\r
852 <programlisting>        \r
853 SELECT\r
854         "aou".id AS "id",\r
855         "aou".name AS "name"\r
856 FROM\r
857         actor.org_unit AS "aou"\r
858 WHERE\r
859         "aou".id IN\r
860         (\r
861                 SELECT\r
862                         "asv".owner AS "owner"\r
863                 FROM\r
864                         action.survey AS "asv"\r
865                 WHERE\r
866                         "asv".name = 'Voter Registration'\r
867         );\r
868 </programlisting>\r
869                 <para>In SQL the subquery may select multiple columns, but in a JSON query it can select only a single column.</para>\r
870                 <para>For a NOT IN clause with a subquery, use the <quote>not in</quote> operator instead of <quote>in</quote>.</para>\r
871         </simplesect>\r
872         <simplesect>\r
873                 <title>Comparing to a Function</title>\r
874                 <para>Here's how to compare a column to a function call:</para>\r
875 <programlisting>        \r
876 {\r
877         "from":"aou",\r
878         "select": { "aou":[ "id", "name" ] },\r
879         "where": {\r
880                 "id":{ ">":[ "sqrt", 16 ] }\r
881          }\r
882 }\r
883 </programlisting>\r
884                 <para>A comparison operator (<quote>&gt;</quote> in this case) is paired with an array. The first entry in the array must be a string giving the name of the function. The remaining parameters, \r
885                 if any, are the parameters. They may be strings, numbers, or nulls. The resulting SQL for this example:</para>\r
886 <programlisting>        \r
887 SELECT\r
888         "aou".id AS "id",\r
889         "aou".name AS "name"\r
890 FROM\r
891         actor.org_unit AS "aou"\r
892 WHERE\r
893         "aou".id > sqrt( '16' );\r
894 </programlisting>\r
895                 <para>All parameters are passed as quoted strings -- even if, as in this case, they are really numbers.</para>\r
896                 <para>This syntax is somewhat limited in that the function parameters must be constants (hence the use of a silly example).</para>\r
897         </simplesect>\r
898         <simplesect>\r
899                 <title>Putting a Function Call on the Left</title>\r
900                 <para>In the discussion of the SELECT clause, we saw how you could transform the value of a selected column by passing it to a function. In the WHERE clause, you can \r
901                 use similar syntax to transform the value of a column before comparing it to something else.</para>\r
902                 <para>For example:</para>\r
903 <programlisting>        \r
904 {\r
905         "from":"aou",\r
906         "select": { "aou":[ "id", "name" ] },\r
907         "where": {\r
908                 "name": {\r
909                         "=": {\r
910                                 "transform":"upper",\r
911                                 "value":"CARTER BRANCH"\r
912                         }\r
913                 }\r
914         }\r
915 }\r
916 </programlisting>\r
917                 <para>The "transform" entry gives the name of the function that we will use on the left side of the comparison. The "value" entry designates the value on the right side \r
918                 of the comparison.</para>\r
919 <programlisting>        \r
920 SELECT\r
921         "aou".id AS "id",\r
922         "aou".name AS "name"\r
923 FROM\r
924         actor.org_unit AS "aou"\r
925 WHERE\r
926         upper("aou".name ) =  'CARTER BRANCH' ;\r
927 </programlisting>\r
928                 <para>As in the SELECT clause, you can pass literal values or nulls to the function as additional parameters by using an array tagged as <quote>params</quote>:</para>\r
929 <programlisting>        \r
930 {\r
931         "from":"aou",\r
932         "select": { "aou":[ "id", "name" ] },\r
933         "where": {\r
934                 "name": {\r
935                         "=": {\r
936                                 "transform":"substr",\r
937                                 "params":[ 1, 6 ],\r
938                                 "value":"CARTER"\r
939                         }\r
940                 }\r
941          }\r
942 }\r
943         \r
944 SELECT\r
945     "aou".id AS "id",\r
946     "aou".name AS "name"\r
947 FROM\r
948     actor.org_unit AS "aou"\r
949 WHERE\r
950     substr("aou".name,'1','6' ) =  'CARTER' ;\r
951 </programlisting>\r
952                 <para>The first parameter is always the column name, qualified by the class name, followed by any additional parameters (which are always enclosed in quotes even if they \r
953                 are numeric).</para>\r
954                 <para>As in the SELECT clause: if the function returns multiple columns, you can specify the one you want by using a "result_field" entry (not shown here).</para>\r
955                 <para>If you leave out the "transform" entry (or misspell it), the column name will appear on the left without any function call. This syntax works, but it's more \r
956                 complicated than it needs to be.</para>\r
957         </simplesect>\r
958 \r
959         <simplesect>\r
960                 <title>Putting Function Calls on Both Sides</title>\r
961                 <para>If you want to compare one function call to another, you can use the same syntax shown in the previous subsection -- except that the <quote>value</quote> entry carries an \r
962                 array instead of a literal value. For example:</para>\r
963 <programlisting>        \r
964 {\r
965         "from":"aou",\r
966         "select": { "aou":[ "id", "name" ] },\r
967         "where": {\r
968                 "id": {\r
969                         "&gt;": {\r
970                                 "transform":"factorial",\r
971                                 "value":[ "sqrt", 1000 ]\r
972                         }\r
973                 }\r
974         }\r
975 }               \r
976 SELECT\r
977     "aou".id AS "id",\r
978     "aou".name AS "name"\r
979 FROM\r
980     actor.org_unit AS "aou"\r
981 WHERE\r
982     factorial("aou".id ) &gt;  sqrt( '1000' ) ;\r
983 </programlisting>\r
984                 <para>The format for the right side function is similar to what we saw earlier, in the subsection Comparing to a Function. Note that there are two different formats \r
985                 for defining function calls:</para>\r
986                 <itemizedlist>\r
987                         <listitem>\r
988                                 <para>For a function call to the left of the comparison, the function name is tagged as <quote>transform</quote>. The first parameter is always the relevant \r
989                                 column name; additional parameters, if any, are in an array tagged as "params". The entry for <quote>result_field</quote>, if present, specifies a subcolumn.</para>    \r
990                         </listitem>\r
991                         <listitem>\r
992                                 <para>For a function call to the right of the comparison, the function name is the first entry in an array, together with any parameters. \r
993                                 There's no way to specify a subcolumn.</para>   \r
994                         </listitem>\r
995                 </itemizedlist> \r
996         </simplesect>\r
997         <simplesect>\r
998                 <title>Comparing a Function to a Condition</title>\r
999                 <para>So far we have seen two kinds of data for the <quote>value</quote> tag. A string or number translates to a literal value, and an array translates to a function call. \r
1000                 The third possibility is a JSON object, which translates to a condition. For example:</para>\r
1001 <programlisting>        \r
1002 {\r
1003         "from":"aou",\r
1004         "select": { "aou":[ "id", "name" ] },\r
1005         "where": {\r
1006                 "id": {\r
1007                          "=": {\r
1008                                 "value":{ "parent_ou":{ ">":3 } },\r
1009                                 "transform":"is_prime"\r
1010                         }\r
1011                 }\r
1012          }\r
1013 }\r
1014 </programlisting>\r
1015                 <para>The function tagged as <quote>transform</quote> must return boolean, or else json_query will generate invalid SQL. The function used here, <quote>is_prime</quote>, \r
1016                 is fictitious.</para>\r
1017 <programlisting>        \r
1018 SELECT\r
1019         "aou".id AS "id",\r
1020         "aou".name AS "name"\r
1021 FROM\r
1022         actor.org_unit AS "aou"\r
1023 WHERE\r
1024 (\r
1025         is_prime("aou".id ) = ( "aou".parent_ou > 3 )\r
1026 );\r
1027 </programlisting>\r
1028                 <para>If we left out the <quote>transform</quote> entry, json_query would compare the column on the left (which would to be boolean) to the condition on the right. The results are similar \r
1029                 to those for a simpler format described earlier (see the subsection Testing Boolean Columns).</para>\r
1030                 <para>In the example above we compared the boolean to a simple condition. However the expression on the right may include multiple conditions, IN lists, subqueries, \r
1031                 and whatever other complications are necessary.</para>\r
1032         </simplesect>\r
1033         <simplesect>\r
1034                 <title>Things You Can't Do</title>\r
1035                 <para>The WHERE clause is subject to some of the same limitations as the SELECT clause. However, in the WHERE clause these limitations are more limiting, because \r
1036                 the client program can't compensate by doing some of the work for itself.</para>\r
1037                 <para>You can't use arbitrary expressions in a WHERE condition, such as "WHERE id &gt; parent_ou -- 3". In some cases you may be able to contrive a custom operator in order to \r
1038                 fake such an expression. However this mechanism is neither very general nor very aesthetic.</para>\r
1039                 <para>To the right of a comparison operator, all function parameters must be literals or null. You can't pass a column value, nor can you nest function calls.</para>\r
1040                 <para>Likewise you can't include column values or arbitrary expressions in an IN list or a BETWEEN clause.</para>\r
1041                 <para>You can't include null values in an IN list or a BETWEEN list, not that you should ever want to.</para>\r
1042                 <para>As noted earlier: you can't use the comparison operators <quote>is distinct from</quote> or <quote>is not distinct from</quote>.</para>\r
1043                 <para>Also as noted earlier: a subquery in an IN clause cannot select more than one column.</para>\r
1044         </simplesect>\r
1045         <simplesect>\r
1046                 <title>JOIN clauses</title>\r
1047                 <para>Until now, our examples have selected from only one table at a time. As a result, the FROM clause has been very simple -- just a single string containing \r
1048                 the class name of the relevant table.</para>\r
1049                 <para>When the FROM clause joins multiple tables, the corresponding JSON naturally gets more complicated.</para>\r
1050                 <para>SQL provides two ways to define a join. One way is to list both tables in the FROM clause, and put the join conditions in the WHERE clause:</para>\r
1051 <programlisting>        \r
1052 SELECT\r
1053         aou.id,\r
1054         aout.name\r
1055 FROM\r
1056         actor.org_unit aou,\r
1057         actor.org_unit_type aout\r
1058 WHERE\r
1059         aout.id = aou.ou_type;\r
1060 </programlisting>\r
1061                 <para>The other way is to use an explicit JOIN clause:</para>\r
1062 <programlisting>        \r
1063 SELECT\r
1064         aou.id,\r
1065         aout.name\r
1066 FROM\r
1067         actor.org_unit aou\r
1068                 JOIN actor.org_unit_type aout\r
1069                         ON ( aout.id = aou.ou_type );\r
1070 </programlisting>\r
1071                 <para>JSON queries use only the second of these methods. The following example expresses the same query in JSON:</para>\r
1072 <programlisting>        \r
1073 {\r
1074         "select": { "aou":[ "id" ], "aout":[ "name" ] },\r
1075         "from": {\r
1076                 "aou":"aout"\r
1077         }\r
1078 }\r
1079 </programlisting>\r
1080                 <para>First, let's review the SELECT clause. Since it selects rows from two different tables, the data for <quote>select</quote> includes two entries, one for each table.</para>\r
1081                 <para>As for the FROM clause, it's no longer just a string. It's a JSON object, with exactly one entry. The key of this entry is the class name of the core table, i.e. \r
1082                 the table named immediately after the FROM keyword. The data associated with this key contains the rest of the information about the join. In this simple example, \r
1083                 that information consists entirely of a string containing the class name of the other table.</para>\r
1084                 <para>So where is the join condition?</para>\r
1085                 <para>It's in the IDL. Upon reading the IDL, json_query knows that actor.org_unit has a foreign key pointing to actor.org_unit_type, and builds a join condition accordingly:</para>\r
1086 <programlisting>        \r
1087 SELECT\r
1088         "aou".id AS "id",\r
1089         "aout".name AS "name"\r
1090 FROM\r
1091         actor.org_unit AS "aou"\r
1092                 INNER JOIN actor.org_unit_type AS "aout"\r
1093                         ON ( "aout".id = "aou".ou_type ) ;\r
1094 </programlisting>\r
1095                 <para>In this case the core table is the child table, and the joined table is the parent table. We could just as well have written it the other way around:</para>\r
1096 <programlisting>        \r
1097 {\r
1098          "select": { "aou":[ "id" ], "aout":[ "name" ] },\r
1099         "from": {\r
1100                 "aout":"aou"\r
1101         }\r
1102 }\r
1103         \r
1104 SELECT\r
1105     "aou".id AS "id",\r
1106     "aout".name AS "name"\r
1107 FROM\r
1108     actor.org_unit_type AS "aout"\r
1109         INNER JOIN actor.org_unit AS "aou"\r
1110             ON ( "aou".ou_type = "aout".id ) ;\r
1111 </programlisting>\r
1112         </simplesect>\r
1113         <simplesect>\r
1114                 <title>Specifying The Join Columns Explicitly</title>\r
1115                 <para>While it's convenient to let json_query pick the join columns, it doesn't always work.</para>\r
1116                 <para>For example, the actor.org_unit table has four different address ids, for four different kinds of addresses. Each of them is a foreign key to the actor.org_address table. \r
1117                 Json_query can't guess which one you want if you don't tell it.</para>\r
1118                 <para>(Actually it will try to guess. It will pick the first matching link that it finds in the IDL, which may or may not be the one you want.)</para>\r
1119                 <para>Here's how to define exactly which columns you want for the join:</para>\r
1120 <programlisting>        \r
1121 {\r
1122         "select": { "aou":[ "id" ], "aoa":[ "street1" ] },\r
1123         "from": {\r
1124                 "aou": {\r
1125                         "aoa": {\r
1126                                 "fkey":"holds_address",\r
1127                                 "field":"id"\r
1128                         }\r
1129                 }\r
1130         }\r
1131 }\r
1132 </programlisting>\r
1133                 <para>Before, the table we were joining was represented merely by its class name. Now it's represented by an entry in a JSON object. The key of that entry is the \r
1134                 class name, and the associated data is another layer of JSON object containing the attributes of the join.</para>\r
1135                 <para>Later we'll encounter other kinds of join attributes. For now, the only attributes that we're looking at are the ones that identify the join columns: \r
1136                 <quote>fkey</quote> and <quote>field</quote>. The hard part is remembering which is which:</para>\r
1137                 <itemizedlist>\r
1138                         <listitem>\r
1139                                 <para><quote>fkey</quote> identifies the join column from the left table;</para>        \r
1140                         </listitem>\r
1141                         <listitem>\r
1142                                 <para><quote>field</quote> identifies the join column from the right table. </para>     \r
1143                         </listitem>\r
1144                 </itemizedlist> \r
1145                 <para>When there are only two tables involved, the core table is on the left, and the non-core table is on the right. In more complex queries neither table may be the \r
1146                 core table.</para>\r
1147                 <para>Here is the result of the preceding JSON:</para>\r
1148 <programlisting>        \r
1149 SELECT\r
1150     "aou".id AS "id",\r
1151     "aoa".street1 AS "street1"\r
1152 FROM\r
1153     actor.org_unit AS "aou"\r
1154         INNER JOIN actor.org_address AS "aoa"\r
1155             ON ( "aoa".id = "aou".holds_address ) ;\r
1156 </programlisting>\r
1157                 <para>In this example the child table is on the left and the parent table is on the right. We can swap the tables if we swap the join columns as well:</para>\r
1158 <programlisting>        \r
1159 {\r
1160         "select": { "aou":[ "id" ], "aoa":[ "street1" ] },\r
1161         "from": {\r
1162                 "aoa": {\r
1163                         "aou": {\r
1164                                 "fkey":"id",\r
1165                                 "field":"holds_address"\r
1166                         }\r
1167                 }\r
1168         }\r
1169 }\r
1170                 \r
1171 SELECT\r
1172     "aou".id AS "id",\r
1173     "aoa".street1 AS "street1"\r
1174 FROM\r
1175     actor.org_address AS "aoa"\r
1176         INNER JOIN actor.org_unit AS "aou"\r
1177             ON ( "aou".holds_address = "aoa".id ) ;\r
1178 </programlisting>\r
1179                 <para>When you specify both of the join columns, json_query assumes that you know what you're doing. It doesn't check the IDL to confirm that the join makes sense. \r
1180                 The burden is on you to avoid absurdities.</para>\r
1181         </simplesect>\r
1182         <simplesect>\r
1183                 <title>Specifying Only One Join Column</title>\r
1184                 <para>We just saw how to specify both ends of a join. It turns out that there's a shortcut -- most of the time you only need to specify one end. Consider \r
1185                 the following variation on the previous example:</para>\r
1186 <programlisting>        \r
1187 {\r
1188         "select": { "aou":[ "id" ], "aoa":[ "street1" ] },\r
1189         "from": {\r
1190                 "aoa": {\r
1191                         "aou": {\r
1192                                 "field":"holds_address"\r
1193                         }\r
1194                 }\r
1195          }\r
1196 }\r
1197 </programlisting>\r
1198                 <para>..which results in exactly the same SQL as before.</para>\r
1199                 <para>Here we specified the join column from the child table, the column that is a foreign key pointing to another table. As long as that linkage is defined in the IDL, \r
1200                 json_query can look it up and figure out what the corresponding column is in the parent table.</para>\r
1201                 <para>However this shortcut doesn't work if you specify only the column in the parent table, because it would lead to ambiguities. Suppose we had specified the id \r
1202                 column of actor.org_address. As noted earlier, there are four different foreign keys from actor.org_unit to actor.org_address, and json_query would have no way to guess \r
1203                 which one we wanted.</para>\r
1204         </simplesect>\r
1205         <simplesect>\r
1206                 <title>Joining to Multiple Tables</title>\r
1207                 <para>So far we have joined only two tables at a time. What if we need to join one table to two different tables?</para>\r
1208                 <para>Here's an example:</para>\r
1209 <programlisting>        \r
1210 {\r
1211         "select": { "aou":[ "id" ], "aout":[ "depth" ], "aoa":[ "street1" ] },\r
1212         "from": {\r
1213                 "aou": {\r
1214                         "aout":{},\r
1215                         "aoa": {\r
1216                                 "fkey":"holds_address"\r
1217                         }\r
1218                 }\r
1219         }\r
1220 }\r
1221 </programlisting>\r
1222                 <para>The first join, to actor.org_unit_type, is simple. We could have specified join columns, but we don't have to, because json_query will construct that join on the basis of \r
1223                 what it finds in the IDL. Having no join attributes to specify, we leave that object empty.</para>\r
1224                 <para>For the second join, to actor.org_address, we have to specify at least the join column in the child table, as discussed earlier. We could also have specified the join \r
1225                 column from the parent table, but we don't have to, so we didn't.</para>\r
1226                 <para>Here is the resulting SQL:</para>\r
1227 <programlisting>        \r
1228 SELECT\r
1229         "aou".id AS "id",\r
1230         "aout".depth AS "depth",\r
1231         "aoa".street1 AS "street1"\r
1232 FROM\r
1233         actor.org_unit AS "aou"\r
1234                 INNER JOIN actor.org_unit_type AS "aout"\r
1235                         ON ( "aout".id = "aou".ou_type )\r
1236                 INNER JOIN actor.org_address AS "aoa"\r
1237                         ON ( "aoa".id = "aou".holds_address ) ;\r
1238 </programlisting>\r
1239                 <para>Since there can be only one core table, the outermost object in the FROM clause can have only one entry, whose key is the class name of the core table. The next \r
1240                 level has one entry for every table that's joined to the core table.</para>\r
1241         </simplesect>\r
1242         <simplesect>\r
1243                 <title>Nested Joins</title>\r
1244                 <para>Let's look at that last query again. It joins three tables, and the core table is the one in the middle. Can we make one of the end tables the core table instead?</para>\r
1245                 <para>Yes, we can:</para>\r
1246 <programlisting>        \r
1247 {\r
1248         "select": { "aou":[ "id" ], "aout":[ "depth" ], "aoa":[ "street1" ] },\r
1249         "from": {\r
1250                 "aoa": {\r
1251                         "aou": {\r
1252                                 "field":"holds_address",\r
1253                                 "join": {\r
1254                                         "aout":{ "fkey":"ou_type" }\r
1255                                 }\r
1256                         }\r
1257                 }\r
1258         }\r
1259 }\r
1260 </programlisting>\r
1261                 <para>The <quote>join</quote> attribute introduces another level of join. In this case "aou" is the left table for the nested join, and the right table for the original join. \r
1262                 Here are the results:</para>\r
1263 <programlisting>        \r
1264 SELECT\r
1265         "aou".id AS "id",\r
1266         "aout".depth AS "depth",\r
1267         "aoa".street1 AS "street1"\r
1268 FROM\r
1269         actor.org_address AS "aoa"\r
1270                 INNER JOIN actor.org_unit AS "aou"\r
1271                         ON ( "aou".holds_address = "aoa".id )\r
1272                                 INNER JOIN actor.org_unit_type AS "aout"\r
1273                                         ON ( "aout".id = "aou".ou_type ) ;\r
1274 </programlisting>\r
1275         </simplesect>\r
1276         <simplesect>\r
1277                 <title>Outer Joins</title>\r
1278                 <para>By default, json_query constructs an inner join. If you need an outer join, you can add the join type as an attribute of the join:</para>\r
1279                 <para>Yes, we can:</para>\r
1280 <programlisting>        \r
1281 {\r
1282         "select": { "aou":[ "id" ], "aoa":[ "street1" ] },\r
1283         "from": {\r
1284                 "aoa": {\r
1285                         "aou": {\r
1286                                 "field":"mailing_address",\r
1287                                 "type":"left"\r
1288                         }\r
1289                 }\r
1290         }\r
1291 }\r
1292 </programlisting>\r
1293                 <para>Here is the resulting SQL for this example:</para>\r
1294 <programlisting>        \r
1295 SELECT\r
1296     "aou".id AS "id",\r
1297     "aoa".street1 AS "street1"\r
1298 FROM\r
1299     actor.org_address AS "aoa"\r
1300         LEFT JOIN actor.org_unit AS "aou"\r
1301             ON ( "aou".mailing_address = "aoa".id ) ;\r
1302 </programlisting>\r
1303         </simplesect>\r
1304         <simplesect>\r
1305                 <title>Referring to Joined Tables in the WHERE Clause</title>\r
1306                 <para>In the WHERE clause of the generated SQL, every column name is qualified by a table alias, which is always the corresponding class name.</para>\r
1307                 <para>If a column belongs to the core table, this qualification happens by default. If it belongs to a joined table, the JSON must specify what class name \r
1308                 to use for an alias. For example:</para>\r
1309 <programlisting>        \r
1310 {\r
1311         "select": { "aou":[ "id" ], "aout":[ "name" ] },\r
1312         "from": {\r
1313                 "aout":"aou"\r
1314         },\r
1315         "where": {\r
1316                 "+aou":{ "parent_ou":2 }\r
1317         }\r
1318 }\r
1319 </programlisting>\r
1320                 <para>Note the peculiar operator <quote>+aou</quote> -- a plus sign followed by the relevant class name. This operator tells json_query to apply the specified class to the condition that \r
1321                 follows. The result:</para>\r
1322 <programlisting>        \r
1323 SELECT\r
1324         "aou".id AS "id",\r
1325         "aout".name AS "name"\r
1326 FROM\r
1327         actor.org_unit_type AS "aout"\r
1328         INNER JOIN actor.org_unit AS "aou"\r
1329                 ON ( "aou".ou_type = "aout".id )\r
1330 WHERE\r
1331         ( "aou".parent_ou = 2 );\r
1332 </programlisting>\r
1333                 <para>The plus-class operator may apply to multiple conditions:</para>\r
1334 <programlisting>        \r
1335 {\r
1336     "select": { "aou":[ "id" ], "aout":[ "name" ] },\r
1337     "from": {\r
1338         "aout":"aou"\r
1339     },\r
1340     "where": {\r
1341         "+aou":{\r
1342             "parent_ou":2,\r
1343             "id":{ "&lt;":42 }\r
1344         }\r
1345     }\r
1346 }\r
1347                 \r
1348 SELECT\r
1349     "aou".id AS "id",\r
1350     "aout".name AS "name"\r
1351 FROM\r
1352     actor.org_unit_type AS "aout"\r
1353         INNER JOIN actor.org_unit AS "aou"\r
1354             ON ( "aou".ou_type = "aout".id )\r
1355 WHERE\r
1356     (\r
1357         "aou".parent_ou = 2\r
1358         AND "aou".id &lt; 42\r
1359     );\r
1360 </programlisting>\r
1361                 <para>For these artificial examples, it would have been simpler to swap the tables, so that actor.org_unit is the core table. Then you wouldn't need to go through any \r
1362                 special gyrations to apply the right table alias. In a more realistic case, however, you might need to apply conditions to both tables. Just swapping the tables \r
1363                 wouldn't solve the problem.</para>\r
1364                 <para>You can also use a plus-class operator to compare columns from two different tables:</para>\r
1365 <programlisting>        \r
1366 {\r
1367     "select": { "aou":[ "id" ], "aout":[ "name" ] },\r
1368     "from": {\r
1369         "aout":"aou"\r
1370     },\r
1371     "where": {\r
1372         "depth": { "&gt;": { "+aou":"parent_ou" } }\r
1373     }\r
1374 }\r
1375                 \r
1376 \r
1377 SELECT\r
1378     "aou".id AS "id",\r
1379     "aout".name AS "name"\r
1380 FROM\r
1381     actor.org_unit_type AS "aout"\r
1382         INNER JOIN actor.org_unit AS "aou"\r
1383             ON ( "aou".ou_type = "aout".id )\r
1384 WHERE\r
1385     (\r
1386         "aout".depth &gt; (  "aou".parent_ou  )\r
1387     );\r
1388 </programlisting>\r
1389                 <para>Please don't expect that query to make any sense. It doesn't. But it illustrates the syntax.</para>\r
1390         </simplesect>\r
1391         <simplesect>\r
1392                 <title>Join Filters</title>\r
1393                 <para>While the above approach certainly works, the special syntax needed is goofy and awkward. A somewhat cleaner solution is to include a condition in the JOIN clause:</para>\r
1394 <programlisting>        \r
1395 {\r
1396     "select": { "aou":[ "id" ], "aout":[ "name" ] },\r
1397     "from": {\r
1398         "aout": {\r
1399             "aou": {\r
1400                 "filter": {\r
1401                     "parent_ou":2\r
1402                 }\r
1403             }\r
1404         }\r
1405     }\r
1406 }                       \r
1407 \r
1408 SELECT\r
1409     "aou".id AS "id", "aout".name AS "name"\r
1410 FROM\r
1411     actor.org_unit_type AS "aout"\r
1412         INNER JOIN actor.org_unit AS "aou"\r
1413             ON ( "aou".ou_type = "aout".id\r
1414                  AND  "aou".parent_ou = 2 ) ;\r
1415 </programlisting>\r
1416                 <para>By default, json_query uses AND to combine the <quote>filter</quote> condition with the original join condition. If you need OR, you can use the <quote>filter_op</quote> attribute to \r
1417                 say so:</para>\r
1418 <programlisting>        \r
1419 {\r
1420     "select": { "aou":[ "id" ], "aout":[ "name" ] },\r
1421     "from": {\r
1422         "aout": {\r
1423             "aou": {\r
1424                 "filter": {\r
1425                     "parent_ou":2\r
1426                 },\r
1427                 "filter_op":"or"\r
1428             }\r
1429         }\r
1430     }\r
1431 }               \r
1432 \r
1433 SELECT\r
1434     "aou".id AS "id",\r
1435     "aout".name AS "name"\r
1436 FROM\r
1437     actor.org_unit_type AS "aout"\r
1438         INNER JOIN actor.org_unit AS "aou"\r
1439             ON ( "aou".ou_type = "aout".id\r
1440                  OR  "aou".parent_ou = 2 ) ;\r
1441 </programlisting>\r
1442                 <para>If the data tagged by <quote>filter_op</quote> is anything but <quote>or</quote> (in upper, lower, or mixed case), json_query uses AND instead of OR.</para>\r
1443                 <para>The condition tagged by <quote>filter</quote> may be much more complicated. In fact it accepts all the same syntax as the WHERE clause.</para>\r
1444                 <para>Remember, though, that it all gets combined with the the original join condition with an AND, or with an OR if you so specify. If \r
1445                 you're not careful, the result may be a confusing mixture of AND and OR at the same level.</para>\r
1446         </simplesect>\r
1447         <simplesect>\r
1448                 <title>Joining to a Subquery</title>\r
1449                 <para>In SQL you can put a subquery in a FROM clause, and select from it as if it were a table. A JSON query has no way to do that directly. The IDL, however, \r
1450                 can define a class as a subquery instead of as a table. When you SELECT from it, json_query inserts the corresponding subquery into the FROM clause. For example:</para>\r
1451 <programlisting>        \r
1452 {\r
1453     "select":{ "iatc":[ "id", "dest", "copy_status" ] },\r
1454     "from": "iatc"\r
1455 }\r
1456 </programlisting>\r
1457                 <para>There's nothing special-looking about this JSON, but json_query expands it as follows:</para>\r
1458 <programlisting>        \r
1459 SELECT\r
1460     "iatc".id AS "id",\r
1461     "iatc".dest AS "dest",\r
1462     "iatc".copy_status AS "copy_status"\r
1463 FROM\r
1464     (\r
1465         SELECT  t.*\r
1466         FROM\r
1467             action.transit_copy t\r
1468                 JOIN actor.org_unit AS s\r
1469                     ON (t.source = s.id)\r
1470                 JOIN actor.org_unit AS d\r
1471                     ON (t.dest = d.id)\r
1472         WHERE\r
1473             s.parent_ou &lt;&gt; d.parent_ou\r
1474     ) AS "iatc" ;\r
1475 </programlisting>\r
1476                 <para>The <quote>iatc</quote> class is like a view, except that it's defined in the IDL instead of the database. In this case it provides a way to do a join that would otherwise be \r
1477                 impossible through a JSON query, because it joins the same table in two different ways (see the next subsection).</para>\r
1478         </simplesect>\r
1479         <simplesect>\r
1480                 <title>Things You Can't Do</title>\r
1481                 <para>In a JOIN, as with other SQL constructs, there are some things that you can't do with a JSON query.</para>\r
1482                 <para>In particular, you can't specify a table alias, because the table alias is always the class name. As a result:</para>\r
1483                 <itemizedlist>\r
1484                         <listitem>\r
1485                                 <para>You can't join a table to itself. For example, you can't join actor.org_unit to itself in order to select the name of the parent for every org_unit.</para>       \r
1486                         </listitem>\r
1487                         <listitem>\r
1488                                 <para>You can't join to the same table in more than one way. For example, you can't join actor.org_unit to actor.org_address through four different foreign \r
1489                                 keys, to get four kinds of addresses in a single query.</para>  \r
1490                         </listitem>\r
1491                 </itemizedlist> \r
1492                 <para>The only workaround is to perform the join in a view, or in a subquery defined in the IDL as described in the previous subsection.</para>\r
1493                 <para>Some other things, while not impossible, require some ingenuity in the use of join filters.</para>\r
1494                 <para>For example: by default, json_query constructs a join condition using only a single pair of corresponding columns. As long as the database is designed accordingly, \r
1495                 a single pair of columns will normally suffice. If you ever need to join on more than one pair of columns, you can use join filters for the extras.</para>      \r
1496                 <para>Likewise, join conditions are normally equalities. In raw SQL it is possible (though rarely useful) to base a join on an inequality, or to use a function call in a join \r
1497                 condition, or to omit any join condition in order to obtain a Cartesian product. If necessary, you can devise such unconventional joins by combining the normal join \r
1498                 conditions with join filters.</para>\r
1499                 <para>For example, here's how to get a Cartesian product:</para>\r
1500 <programlisting>        \r
1501 {\r
1502     "select": { "aou":[ "id" ], "aout":[ "name" ] },\r
1503     "from": {\r
1504         "aout": {\r
1505             "aou": {\r
1506                 "filter": {\r
1507                     "ou_type":{ "&lt;&gt;": { "+aout":"id" } }\r
1508                 },\r
1509                 "filter_op":"or"\r
1510             }\r
1511         }\r
1512     }\r
1513 }\r
1514         \r
1515 \r
1516 SELECT\r
1517     "aou".id AS "id",\r
1518     "aout".name AS "name"\r
1519 FROM\r
1520     actor.org_unit_type AS "aout"\r
1521         INNER JOIN actor.org_unit AS "aou"\r
1522             ON\r
1523             (\r
1524                 "aou".ou_type = "aout".id\r
1525                 OR  ("aou".ou_type &lt;&gt; (  "aout".id  ))\r
1526             ) ;\r
1527 </programlisting>\r
1528                 <para>Yes, it's ugly, but at least you're not likely to do it by accident.</para>\r
1529         </simplesect>\r
1530         <simplesect>\r
1531                 <title>Selecting from Functions</title>\r
1532                 <para>In SQL, you can put a function call in the FROM clause. The function may return multiple columns and multiple rows. Within the query, the function behaves like a table.</para>\r
1533                 <para>A JSON query can also select from a function:</para>\r
1534 <programlisting>        \r
1535 {\r
1536     "from": [ "actor.org_unit_ancestors", 5 ]\r
1537 }\r
1538 </programlisting>\r
1539                 <para>The data associated with <quote>from</quote> is an array instead of a string or an object. The first element in the array specifies the name of the function. Subsequent elements, \r
1540                 if any, supply the parameters of the function; they must be literal values or nulls.</para>\r
1541                 <para>Here is the resulting query:</para>\r
1542 <programlisting>        \r
1543 SELECT *\r
1544 FROM\r
1545         actor.org_unit_ancestors( '5' ) AS "actor.org_unit_ancestors" ;\r
1546 </programlisting>\r
1547                 <para>In a JSON query this format is very limited, largely because the IDL knows nothing about the available functions. You can't join the function to a table or to \r
1548                 another function. If you try to supply a SELECT list or a WHERE clause, json_query will ignore it. The generated query will always select every column, via a wild card asterisk, \r
1549                 from every row.</para>\r
1550         </simplesect>\r
1551         <simplesect>\r
1552                 <title>The ORDER BY Clause</title>\r
1553                 <para>In most cases you can encode an ORDER BY clause as either an array or an object. Let's take a simple example and try it both ways. First the array:</para>\r
1554 <programlisting>        \r
1555 {\r
1556     "select":{ "aou":[ "name" ] },\r
1557     "from": "aou",\r
1558     "order_by": [\r
1559         { "class":"aou", "field":"name" }\r
1560     ]\r
1561 }\r
1562 </programlisting>\r
1563                 <para>Now the object:</para>\r
1564 <programlisting>        \r
1565 {\r
1566     "select":{ "aou":[ "name" ] },\r
1567     "from": "aou",\r
1568     "order_by": {\r
1569         "aou":{ "name":{} }\r
1570     }\r
1571 }\r
1572 </programlisting>\r
1573                 <para>The results are identical from either version:</para>\r
1574 <programlisting>        \r
1575 SELECT\r
1576     "aou".name AS "name"\r
1577 FROM\r
1578     actor.org_unit AS "aou"\r
1579 ORDER BY\r
1580     "aou".name;\r
1581 </programlisting>\r
1582                 <para>The array format is more verbose, but as we shall see, it is also more flexible. It can do anything the object format can do, plus some things that the object \r
1583                 format can't do.</para>\r
1584         </simplesect>\r
1585         <simplesect>\r
1586                 <title>ORDER BY as an Array</title>\r
1587                 <para>In the array format, each element of the array is an object defining one of the sort fields. Each such object must include at least two tags:</para>\r
1588                 <itemizedlist>\r
1589                         <listitem>\r
1590                                 <para>The <quote>class</quote> tag provides the name of the class, which must be either the core class or a joined class.</para>        \r
1591                         </listitem>\r
1592                         <listitem>\r
1593                                 <para>The <quote>field</quote> tag provides the field name, corresponding to one of the columns of the class.</para>    \r
1594                         </listitem>\r
1595                 </itemizedlist> \r
1596                 <para>If you want to sort by multiple fields, just include a separate object for each field.</para>\r
1597                 <para>If you want to sort a field in descending order, add a <quote>direction</quote> tag:</para>\r
1598 <programlisting>        \r
1599 {\r
1600     "select":{ "aou":[ "name" ] },\r
1601     "from": "aou",\r
1602     "order_by": [\r
1603         {\r
1604             "class":"aou",\r
1605             "field":"name",\r
1606             "transform":"upper"\r
1607         }\r
1608     ]\r
1609 }\r
1610                 \r
1611 \r
1612 SELECT\r
1613     "aou".name AS "name"\r
1614 FROM\r
1615     actor.org_unit AS "aou"\r
1616 ORDER BY\r
1617     upper("aou".name );\r
1618 </programlisting>\r
1619                 <para>If you need additional parameters for the function, you can use the <quote>params</quote> tag to pass them:</para>\r
1620 <programlisting>        \r
1621 {\r
1622     "select":{ "aou":[ "name" ] },\r
1623     "from": "aou",\r
1624     "order_by": [\r
1625         {\r
1626             "class":"aou",\r
1627             "field":"name",\r
1628             "transform":"substr",\r
1629             "params":[ 1, 8 ]\r
1630         }\r
1631     ]\r
1632 }\r
1633 </programlisting>\r
1634                 <para>The additional parameters appear as elements in an array. They may be numbers, strings, or nulls.</para>\r
1635 <programlisting>        \r
1636 SELECT\r
1637     "aou".name AS "name"\r
1638 FROM\r
1639     actor.org_unit AS "aou"\r
1640 ORDER BY\r
1641     substr("aou".name,'1','8' );\r
1642 </programlisting>\r
1643                 <para>As we have seen elsewhere, all literal values are passed as quoted strings, even if they are numbers.</para>\r
1644                 <para>If the function returns multiple columns, you can use the <quote>result_field</quote> tag to indicate which one you want (not shown).</para>\r
1645         </simplesect>\r
1646 \r
1647         <simplesect>\r
1648                 <title>ORDER BY as an Object</title>\r
1649                 <para>When you encode the ORDER BY clause as an object, the keys of the object are class names. Each class must be either the core class or a joined class. The data for \r
1650                 each class can be either an array or another layer of object. Here's an example with one of each:</para>\r
1651 <programlisting>        \r
1652 {\r
1653     "select":{ "aout":"id", "aou":[ "name" ] },\r
1654     "from": { "aou":"aout" },\r
1655     "order_by": {\r
1656         "aout":[ "id" ],\r
1657         "aou":{ "name":{ "direction":"desc" } }\r
1658     }\r
1659 }\r
1660 </programlisting>\r
1661                 <para>For the <quote>aout</quote> class, the associated array is simply a list of field names (in this case, just one). Naturally, each field must reside in the class with which \r
1662                 it is associated.</para>\r
1663                 <para>However, a list of field names provides no way to specify the direction of sorting, or a transforming function. You can add those details only if the class \r
1664                 name is paired with an object, as in the example for the "aou" class. The keys for such an object are field names, and the associated tags define other details.</para>\r
1665                 <para>In this example, we use the <quote>direction"</quote> tag to specify that the name field be sorted in descending order. This tag works the same way here as described earlier. \r
1666                 If the associated string starts with "D" or "d", the sort will be descending; otherwise it will be ascending.</para>\r
1667                 <para>Here is the resulting SQL:</para>\r
1668 <programlisting>        \r
1669 SELECT\r
1670     "aou".name AS "name"\r
1671 FROM\r
1672     actor.org_unit AS "aou"\r
1673         INNER JOIN actor.org_unit_type AS "aout"\r
1674             ON ( "aout".id = "aou".ou_type )\r
1675 ORDER BY\r
1676     "aout".id,\r
1677     "aou".name DESC;\r
1678 </programlisting>\r
1679 <programlisting>\r
1680 {\r
1681     "select":{ "aou":[ "name", "id" ] },\r
1682     "from": "aou",\r
1683     "order_by": {\r
1684         "aou":{\r
1685             "name":{ "transform":"substr", "params":[ 1, 8 ] }\r
1686         }\r
1687     }\r
1688 }                       \r
1689 \r
1690 SELECT\r
1691     "aou".name AS "name",\r
1692     "aou".id AS "id"\r
1693 FROM\r
1694     actor.org_unit AS "aou"\r
1695 ORDER BY\r
1696     substr("aou".name,'1','8' );\r
1697 </programlisting>\r
1698         </simplesect>\r
1699         <simplesect>\r
1700                 <title>Things You Can't Do</title>\r
1701                 <para>If you encode the ORDER BY clause as an object, you may encounter a couple of restrictions.</para>\r
1702                 <para>Because the key of such an object is the class name, all the fields from a given class must be grouped together. You can't sort by a column from one table, followed by \r
1703                 a column from another table, followed by a column from the first table. If you need such a sort, you must encode the ORDER BY clause in the array format, which suffers \r
1704                 from no such restrictions.</para>\r
1705                 <para>For similar reasons, with an ORDER BY clause encoded as an object, you can't reference the same column more than once. Although such a sort may seem perverse, \r
1706                 there are situations where it can be useful, provided that the column is passed to a transforming function.</para>\r
1707                 <para>For example, you might want a case-insensitive sort, except that for any given letter you want lower case to sort first. For example, you want <quote>diBona</quote> to sort \r
1708                 before <quote>Dibona</quote>. Here's a way to do that, coding the ORDER BY clause as an array:</para>\r
1709 <programlisting>        \r
1710 {\r
1711     "select":{ "au":[ "family_name", "id" ] },\r
1712     "from": "au",\r
1713     "order_by": [\r
1714         { "class":"au", "field":"family_name", "transform":"upper" },\r
1715         { "class":"au", "field":"family_name" }\r
1716     ]\r
1717 }\r
1718 SELECT\r
1719         "au".family_name AS "family_name",\r
1720         "au".id AS "id"\r
1721 FROM\r
1722         actor.usr AS "au"\r
1723 ORDER BY\r
1724         upper("au".family_name ),\r
1725         "au".family_name;\r
1726 </programlisting>\r
1727                 <para>Such a sort is not possible where the ORDER BY clause is coded as an object.</para>\r
1728         </simplesect>\r
1729         <simplesect>\r
1730                 <title>The GROUP BY Clause</title>\r
1731                 <para>A JSON query has no separate construct to define a GROUP BY clause. Instead, the necessary information is distributed across the SELECT clause. However, \r
1732                 the way it works is a bit backwards from what you might expect, so pay attention.</para>\r
1733                 <para>Here's an example:</para>\r
1734 <programlisting>        \r
1735 {\r
1736     "select": {\r
1737         "aou": [\r
1738             { "column":"parent_ou" },\r
1739             { "column":"name", "transform":"max", "aggregate":true }\r
1740         ]\r
1741     },\r
1742     "from": "aou"\r
1743 }\r
1744 </programlisting>\r
1745                 <para>The <quote>transform</quote> tag is there just to give us an excuse to do a GROUP BY. What's important to notice is the <quote>aggregate</quote> tag.</para>\r
1746                 <para>Here's the resulting SQL:</para>\r
1747 <programlisting>        \r
1748 SELECT\r
1749     "aou".parent_ou AS "parent_ou",\r
1750     max("aou".name ) AS "name"\r
1751 FROM\r
1752     actor.org_unit AS "aou"\r
1753 GROUP BY\r
1754     1;\r
1755 </programlisting>\r
1756                 <para>The GROUP BY clause references fields from the SELECT clause by numerical reference, instead of by repeating them. Notice that the field it references, \r
1757                 parent_ou, is the one that doesn't carry the <quote>aggregate</quote> tag in the JSON.</para>\r
1758                 <para>Let's state that more generally. The GROUP BY clause includes only the fields that do not carry the <quote>aggregate</quote> tag (or that carry it with a value of false).</para>\r
1759                 <para>However, that logic applies only when some field somewhere does carry the <quote>aggregate</quote> tag, with a value of true. If there is no <quote>aggregate</quote> tag, or \r
1760                 it appears only with a value of false, then there is no GROUP BY clause.</para>\r
1761                 <para>If you really want to include every field in the GROUP BY clause, don't use <quote>aggregate</quote>. Use the <quote>distinct</quote> tag, as described in the next section.</para>\r
1762         </simplesect>\r
1763         <simplesect>\r
1764                 <title>The DISTINCT Clause</title>\r
1765                 <para>JSON queries don't generate DISTINCT clauses. However, they can generate GROUP BY clauses that include every item from the SELECT clause. The effect is the same as \r
1766                 applying DISTINCT to the entire SELECT clause.</para>\r
1767                 <para>For example:</para>\r
1768 <programlisting>        \r
1769 {\r
1770     "select": {\r
1771         "aou": [\r
1772             "parent_ou",\r
1773             "ou_type"\r
1774         ]\r
1775     },\r
1776     "from":"aou",\r
1777     "distinct":"true"\r
1778 }\r
1779 </programlisting>\r
1780                 <para>Note the <quote>distinct</quote> entry at the top level of the query object, with a value of <quote>true</quote>.</para>\r
1781 <programlisting>        \r
1782 SELECT\r
1783     "aou".parent_ou AS "parent_ou",\r
1784     "aou".ou_type AS "ou_type"\r
1785 FROM\r
1786     actor.org_unit AS "aou"\r
1787 GROUP BY\r
1788     1, 2;\r
1789 </programlisting>\r
1790                 <para>The generated GROUP BY clause references every column in the SELECT clause by number.</para>\r
1791         </simplesect>\r
1792         <simplesect>\r
1793                 <title>The HAVING Clause</title>\r
1794                 <para>For a HAVING clause, add a <quote>having</quote> entry at the top level of the query object. For the associated data, you can use all the same syntax \r
1795                 that you can use for a WHERE clause.</para>\r
1796                 <para>Here's a simple example:</para>\r
1797 <programlisting>        \r
1798 {\r
1799     "select": {\r
1800         "aou": [\r
1801             "parent_ou", {\r
1802                 "column":"id",\r
1803                 "transform":"count",\r
1804                 "alias":"id_count",\r
1805                 "aggregate":"true"\r
1806             }\r
1807         ]\r
1808     },\r
1809     "from":"aou",\r
1810     "having": {\r
1811         "id": {\r
1812             "&gt;" : {\r
1813                 "transform":"count",\r
1814                 "value":6\r
1815             }\r
1816         }\r
1817     }\r
1818 }\r
1819 </programlisting>\r
1820                 <para>We use the <quote>aggregate</quote> tag in the SELECT clause to give us a GROUP BY to go with the HAVING. Results:</para>\r
1821 <programlisting>        \r
1822 SELECT\r
1823     "aou".parent_ou AS "parent_ou",\r
1824     count("aou".id ) AS "id_count"\r
1825 FROM\r
1826     actor.org_unit AS "aou"\r
1827 GROUP BY\r
1828     1\r
1829 HAVING\r
1830     count("aou".id ) &gt;  6 ;\r
1831 </programlisting>\r
1832                 <para>In raw SQL we could have referred to <quote>count( 1 )</quote>. But since JSON queries cannot encode arbitrary expressions, we applied the count function to a column that \r
1833                 cannot be null.</para>\r
1834         </simplesect>\r
1835         <simplesect>\r
1836                 <title>The LIMIT and OFFSET Clauses</title>\r
1837                 <para>To add an LIMIT or OFFSET clause, add an entry to the top level of a query object. For example:</para>\r
1838 <programlisting>        \r
1839 {\r
1840     "select": {\r
1841         "aou": [ "id", "name" ]\r
1842     },\r
1843     "from":"aou",\r
1844     "order_by": { "aou":[ "id" ] },\r
1845     "offset": 7,\r
1846     "limit": 42\r
1847 }\r
1848 </programlisting>\r
1849                 <para>The data associated with <quote>offset</quote> and <quote>limit</quote> may be either a number or a string, but if it's a string, it should have a number inside.</para>\r
1850                 <para>Result:</para>\r
1851 <programlisting>        \r
1852 SELECT\r
1853    "aou".id AS "id",\r
1854    "aou".name AS "name"\r
1855 FROM\r
1856    actor.org_unit AS "aou"\r
1857 ORDER BY\r
1858    "aou".id\r
1859 LIMIT 42 \r
1860 OFFSET 7;\r
1861 </programlisting>\r
1862         </simplesect>\r
1863 </chapter>\r