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