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