root / manual / manual.tex @ e27cb406a8e0181c7880525ed996d20947ed7214

View | Annotate | Download (372.7 KB)

1
% APQ-2.2 Manual
2
3
\documentclass[english,letterpaper]{book}
4
\usepackage{times}
5
\usepackage[T1]{fontenc}
6
\usepackage[latin1]{inputenc}
7
\usepackage{longtable}
8
\usepackage{amsmath}
9
\usepackage{amssymb}
10
11
\usepackage{floatflt}
12
\usepackage{fancyhdr}
13
14
\pagestyle{fancy}
15
16
%\lhead{}
17
%\chead{}
18
\rhead{}
19
20
\lfoot{}
21
\cfoot{\thepage}
22
\rfoot{APQ 2.2}
23
24
25
\newcommand\Ref[1]{\textsection\ref{#1} (page~\pageref{#1})}
26
27
\usepackage{fancyvrb}
28
29
\usepackage{makeidx}
30
\makeindex
31
32
\IfFileExists{url.sty}{\usepackage{url}}
33
                      {\newcommand{\url}{\texttt}}
34
35
\makeatletter
36
37
\usepackage{babel}
38
\makeatother
39
40
\DefineVerbatimEnvironment{SQL}{Verbatim}%
41
   {frame=single,fontsize=\small,label={SQL},labelposition=topline}
42
\DefineVerbatimEnvironment{Code}{Verbatim}%
43
   {frame=single,fontsize=\small}
44
\DefineVerbatimEnvironment{Example}{Verbatim}%
45
   {frame=single,fontsize=\small,label={Example},labelposition=topline}
46
\DefineVerbatimEnvironment{NumberedExample}{Verbatim}%
47
   {frame=single,numbers=left,fontsize=\small,label={Example},labelposition=topline,commandchars=\\\{\}}
48
49
\begin{document}
50
51
\title{APQ Ada95 Database Binding}
52
\author{Copyright (c) 2002-2004, Warren W. Gay VE3WWG}
53
\date{\today}
54
\maketitle
55
56
\tableofcontents{}
57
\listoftables
58
%\listoffigures
59
60
\chapter{Introduction}
61
62
63
\section{APQ Version 2.2}
64
65
This manual documents APQ Version 2.2, which is released under a dual
66
ACL\index{ACL} and GPL\index{GPL} (GNU Public License)\index{GNU Public
67
License} arrangement. The dual license arrangement is designed to give
68
both the \index{distributor} and user the necessary freedoms to enjoy
69
the fair use and distribution of the sources \index{distribution of
70
sources} contained in this project. See file COPYING\index{copying} for
71
more details.
72
73
74
\section{Supported Databases}
75
76
The APQ binding\index{binding} was initially created to satisfy the simple need to
77
allow Ada\index{Ada} programs to use a PostgreSQL\index{PostgreSQL} database. However, as open
78
sourced database technologies continue to advance, the need to allow
79
other databases to be used, becomes greater. Rather than write a unique
80
Ada binding for each one, it was conceptualized that a common API\index{API}
81
could emerge from the APQ framework\index{framework}. To this end, the APQ binding
82
has been reworked rather extensively for version 2.1, to permit increasing
83
levels of general support of other database technologies, including
84
MySQL\index{MySQL}.
85
86
In the fall of 2003 the foundation was laid for Sybase\index{Sybase} support in
87
the unreleased APQ 2.2 software using Sybase on a trial download\index{download} basis.
88
Sybase highlighted some new APQ design \index{design, APQ} wrinkles, which required a
89
few new adjustments and API additions. However, this development ground
90
to a halt for a spell, until September 9, 2004 when it was announced
91
on www.slashdot.org\index{www.slashdot.org} that ``Sybase Releases Free Enterprise Database
92
on Linux''\index{Linux}.
93
94
\begin{quote}
95
``Sybase announced today that they are releasing a free (as in
96
beer) version of their flagship database for Linux. The free version
97
is limited to 1 CPU, 2 GB of RAM, and 5 GB of data, which is more
98
than adequate for all but the most demanding applications. This release
99
provides a very attractive alternative to Microsoft SQL Server\index{Microsoft SQL Server}, and
100
gives developers and DBAs an extremely powerful argument to use against
101
the adoption of Microsoft-based solutions.''%
102
\footnote{Posted by ``Tassach'' (tassach@rapiertech.com)}
103
\end{quote}
104
105
Now there was greater reason to put enterprise class database support
106
into an Ada thick binding\index{thick binding} for databases. Sybase support in APQ would
107
allow developers to develop real applications in using Ada, without
108
trial software expiring. Once developed, these same Ada applications
109
could be deployed within the enterprise and on a large scale.
110
111
\begin{floatingtable}{
112
   \begin{tabular}{lccc}
113
   Database       &  As of APQ Version &  SQL   &  Blob\\
114
   \hline
115
   PostgreSQL     &  1.x               &  Yes   &  Yes\\
116
   MySQL          &  2.x               &  Yes   &  No\\
117
   Sybase 12.52   &  2.2               &  Yes   &  No\\
118
   \end{tabular}}
119
   \caption{Database Product Support}\label{t:DBSupport}
120
\end{floatingtable}
121
122
Thanks in part to the generosity of Sybase to developers, APQ 2.2
123
now supports the following list of database\index{list of database technologies} technologies:
124
Table \ref{t:DBSupport} is further described as follows:
125
126
\begin{description}
127
   \item [As of APQ Version]is the version where the database was first supported.
128
   \item [SQL]indicates whether the common SQL functions are supported (sans blob).
129
   \item [Blob]indicates whether blob support is present.
130
\end{description}
131
132
As the reader can observe in the table above, the support for MySQL
133
is incomplete in APQ 2.1. The blob support\index{blob support} is lacking in APQ for MySQL,
134
because MySQL's blob interface is not as complete as provided by PostgreSQL.
135
Where PostgreSQL provides the facility for virtually limitless sized
136
blobs, a MySQL blob must fit within a ``column'', very much like
137
a text field. For this reason, the facility to perform stream oriented\index{stream oriented}
138
I/O is lacking on a blob in APQ for MySQL.
139
140
141
\subsection{The Future of Blob Support for MySQL}
142
143
Much investigation and research\index{research, APQ} is required to adequately resolve
144
the blob issue in APQ. Rather than hold back the binding from general
145
use, where blob functionality may have limited use anyway, it was
146
decided to release APQ 2.0 with the common API for the two databases,
147
and leaving the resolution of the blob API for a future release.
148
149
If you are a developer, who hopes to write portable database\index{portable database code} code,
150
then please be aware that the PostgreSQL\index{PostgreSQL} blob\index{blob} API is subject to future
151
revision. Potentially, this could be fairly extensively revised, but
152
every attempt will be made to leave a migration path open to the developer.
153
154
155
\section{Generic Database Support}
156
157
One of the main goals of the APQ version 2.0 release, was to develop
158
a common API\index{API, common}, that does not discriminate based upon the database technology
159
being selected. The ideal was to allow a developer to write a procedure
160
that would accept a classwide\index{classwide} database objects, and perform database
161
operations without needing to be concerned whether the database being
162
used was PostgreSQL\index{PostgreSQL}, MySQL\index{MySQL} or Sybase\index{Sybase}.
163
To a large extent, the author believes that this goal has been achieved.
164
165
166
\subsection{Generic Limitations}
167
168
It must be admited however, there are some areas where the database
169
technologies were very different. Consequently, some exceptions and
170
work-arounds will be required by the programmer. An example of this
171
is that MySQL\index{MySQL} requires that all rows be fetched from a SELECT\index{SELECT} query.
172
A failure to do this, corrupts the communication between the server\index{communication, server}
173
and the client. Consequently, APQ works around this by defaulting
174
to use the C library call mysql\_store\_result()\index{mysql\_store\_result()} instead of the alternative,
175
which is mysql\_use\_result()\index{mysql\_use\_result()}. However, if the result set is large,\index{large result sets}
176
then receiving all of the rows into the clients memory\index{memory, client} is not a suitable
177
choice. Consequently, APQ does provide some MySQL specific ways to
178
manage this setting. 
179
180
The MySQL database software also provides the special ``LIMIT n''\index{LIMIT n}
181
extension, if the client program is only interested in the first n
182
rows of the result. If for example, you have a price file containing
183
stock price history, you may want to query the most recent price for
184
it. The simplest way to do this would be to perform a SELECT\index{SELECT} on the
185
table with a descending price date sort sequence (or index). But if
186
you only want the first (most recent) row \index{most recent row} returned, you do not want
187
to retrieve the entire price history into the memory of your client!
188
This is what mysql\_store\_result()\index{mysql\_store\_result()} implies (APQ default). So the
189
application programmer will need to plan for this, when MySQL is used.
190
He will need to do one of the following:
191
192
\begin{itemize}
193
   \item Cause mysql\_use\_result() to be used instead (change the APQ default),
194
         and then fetch all of the rows, one by one.
195
   \item Use the MySQL ``LIMIT 1''\index{LIMIT n} SQL extension to limit the results to
196
         1 row.
197
\end{itemize}
198
199
The problem of course, is that this type of handling must only be
200
done for MySQL\index{MySQL} databases. Consequently, APQ also provides an API so
201
that the application may query which database is being used.
202
203
204
\section{The APQ Database Binding}
205
206
This software represents a binding\index{binding to objects} to objects and procedures that
207
enable the Ada95\index{Ada95}%
208
\footnote{Hereafter, we'll just refer to the language as Ada, even though the
209
version of the language implied is Ada95.%
210
} programmer to manipulate or query a relational database.\index{relational database} This document
211
describes the design principles and goals\index{goals of APQ} of this APQ binding. It
212
also supplies reference documentation\index{reference documentation} to the programmer, enabling
213
the reader to write applications using the PostgreSQL\index{PostgreSQL}, MySQL\index{MySQL} 
214
or Sybase\index{Sybase}  databases,
215
in the Ada programming language.
216
217
The APQ binding\index{binding} was initially developed using GNAT
218
3.13p\index{GNAT} under FreeBSD 4.4\index{FreeBSD} release.
219
APQ version 2.0 was developed using Debian\index{Debian Linux} Linux\index{Linux} and GNAT 3.14p. The
220
examples presented will be tested under the same development environments.
221
222
The source code avoids any use of GNAT\index{GNAT} specific language extensions\index{language extensions}.
223
The possible exception to this rule is that the gnatprep\index{gnatprep} tool may
224
be used to precompile\index{precompile} optional support of optional databases\index{optional databases}. There
225
is some C\index{C language} language source\index{source code} code used, to facilitate Ada\index{Ada} and database
226
C language library linkages.
227
228
\begin{table}
229
   \begin{center}
230
   \begin{tabular}{ll}
231
   Library           &  Database\\
232
   \hline 
233
   libpq             &  PostgreSQL\\
234
   libmysqlclient    &  MySQL\\
235
   OCS-12\_5         &  Sybase\\
236
   \end{tabular}
237
   \end{center}
238
\caption{Client Libraries}\label{t:ClientLib}
239
\end{table}
240
241
Table \ref{t:ClientLib} 
242
lists the C language libraries\index{libraries, C} that are
243
used in addition to the APQ client\index{library, APQ client} library, while linking\index{linking} your
244
application:
245
246
GNAT specific features are avoided where possible. The exception
247
however, is the use of the GNAT\index{GNAT} specific pragma\index{pragma} statements of the form:
248
249
\index{Linker\_Options}
250
\begin{Code}
251
252
   pragma Linker_Options("-lapq");
253
254
\end{Code}
255
256
is used for example, to save the programmer from having to specify
257
linking\index{linking} arguments. Therefore those using non-ACT\index{non-ACT} vendor
258
supplied Ada compilers\index{Ada compilers} might be able to compile and use this binding\index{binding}
259
without a huge investment.
260
261
A 32-bit\index{32-bit Windows} Windows library for APQ can be built for use with the PostgreSQL\index{PostgreSQL},
262
MySQL\index{MySQL} or Sybase\index{Sybase} DLL\index{DLL} client libraries. APQ release 2.1 included the
263
win32 build instructions necessary, but was omitted in the 2.0 release.
264
265
266
\subsection{General Features}
267
268
This binding\index{binding} supports all of the normal database functions that a
269
programmer would want to use. Additionally blob\index{blob} support
270
is included%
271
\footnote{For PostgreSQL only, at release 2.0.%
272
}, and implemented using the Ada streams\index{streams, Ada} interface\index{interface}.
273
This provides the programmer with the Ada convenience and safety of
274
the streams interface\index{streams interface} when working with blobs.
275
276
This binding includes the following general features:
277
278
\begin{enumerate}
279
   \item Open and Close one or more concurrent database connections\index{connections}
280
   \item Create and Execute one or more concurrent SQL queries\index{queries, concurrent} on a selected
281
         database connection\index{connection, database}
282
   \item Begin work\index{begin work}, Commit work\index{commit work} or Rollback work\index{rollback work}
283
   \item Access error message\index{error messages} text
284
   \item Generic functions and procedures to support specialized application
285
         types
286
   \item The NULL indicator\index{NULL indicator} is supported
287
   \item Blob\index{blob} support using the Ada streams\index{streams, Ada} facility
288
   \item A wide range of native\index{native types} and builtin\index{builtin data types} data types are supported
289
   \item Database neutral API\index{neutral API, database} is now supported for most functions
290
\end{enumerate}
291
292
\subsection{Binding Type}
293
294
This library represents a thick Ada binding\index{thick binding} to the PostgreSQL C\index{C programmer}  programmer's
295
libpq\index{libpq} library %
296
\footnote{C++ programs can also make use of this library but there exists the
297
library libpq++ for C++ native support.%
298
}, and with version 2.0, MySQL's\index{MySQL} C programming library. As a thick
299
binding, there are consequently Ada objects\index{objects, Ada} and data types that are
300
tailored specifically to the Ada programmer. Some data types and objects
301
exist to mirror those used in the C language, while others are provided
302
to make the binding easier or safer to apply.
303
304
A thin binding\index{thin binding} would have required the Ada programmer to be continually
305
dealing with C language\index{C language data types} data type issues. Conversions to and from
306
various types and pointers\index{pointers} would be necessary making the use of the
307
binding rather tedious. Furthermore, the resulting Ada\index{Ada} program would
308
be much harder to read and understand.
309
310
A thick binding\index{thick binding} introduces new objects and types in order to provide
311
an API to the programmer. This approach however, fully insulates the
312
Ada\index{Ada} programmer from interfacing with C programs\index{C programs}, pointers\index{pointers} and strings\index{strings}.
313
The design goal\index{design goal} has additionally been to keep the number of new objects
314
and types to a minimum. This has been done without sacrificing convenience
315
and safety\index{safety}. Readability\index{readability} of the resulting Ada\index{Ada} program was also considered
316
to be important.
317
318
The objects and data types involved in the use of this binding can
319
be classified into the following main groups:
320
321
\begin{enumerate}
322
   \item Native\index{native data types} data types and objects
323
   \item Database \index{database objects} manipulation objects
324
   \item New database related objects and types for holding data
325
\end{enumerate}
326
327
Native data types need no explanation in this document. The database
328
manipulation objects will be described in 
329
\Ref{Database_Objects:Section}.
330
The following section will introduce the Ada types\index{Ada types} that are used to
331
hold data.
332
333
334
\section{Binding Data Types}
335
336
The PostgreSQL\index{PostgreSQL} database supports many standard SQL\index{SQL data types} data types as well
337
as a few exotic ones. This section documents the database base types\index{data types, database}
338
that are supported by the Ada\index{Ada binding} binding to the database. This list is
339
expected to grow with time as the Ada binding continues to mature
340
in its own software development.
341
342
The ``Data Type Name'' column in the following table refers to
343
a binding type\index{binding type} if the type name is prefixed with ``APQ\_''%
344
\footnote{Formerly, the PostgreSQL specific types had used a PG\_ prefix.%
345
}. These data types were designed to mimic common database data types
346
in use. They can be used as they are provided, or you may subtype
347
from them or even derive new types from them in typical Ada\index{Ada} fashion.
348
All other data types are references to native Ada data types (for
349
some of these, the package where they are defined are shown in the
350
``Notes'' column).
351
352
The column labelled ``Root Type''\index{root types} documents the data type that
353
the APQ\_ data type was derived\index{derived} from. Where they represent an Ada\index{subtype, Ada}
354
subtype, the column ``Subtype'' indicates a ``Y''. For type
355
derivations a ``N'' is shown in this column, indicating that the
356
APQ\_ type \index{APQ\_ types} listed is made ``unique''.
357
358
359
\subsection{PostgreSQL Data Types\label{PostgreSQL SQL Data Types}}
360
361
The ``Notes'' column of Table \ref{t:pqtypes} provides PostgreSQL notes, package names\index{package names} and
362
PostgreSQL\index{data types, PostgreSQL} data type names where the name is given in all capitals.
363
364
\begin{longtable}{|l|c|c|l|}
365
\hline 
366
Data Type Name    &  Root Type   &  Subtype  &  PostgreSQL Notes\\
367
\hline \hline 
368
Row\_ID\_Type     &  -           &  N        &  Used for blobs and rows\\
369
\hline 
370
String(<>)        &  -           &  -        &  Native Strings\\
371
\hline 
372
String(a..b)      &  -           &  -        &  Fixed length strings\\
373
\hline 
374
Unbounded\_String &  -           &  -        &  Ada.Strings.Unbounded\\
375
\hline 
376
Bounded\_String   &  -           &  -        &  Ada.Strings.Bounded\\
377
\hline 
378
APQ\_Smallint     &  -           &  N        &  SMALLINT\\
379
\hline 
380
APQ\_Integer      &  -           &  N        &  INTEGER\\
381
\hline 
382
APQ\_Bigint       &  -           &  N        &  BIGINT\\
383
\hline 
384
APQ\_Real         &  -           &  N        &  REAL\\
385
\hline 
386
APQ\_Double       &  -           &  N        &  DOUBLE PRECISION\\
387
\hline 
388
APQ\_Serial       &  -           &  N        &  SERIAL\\
389
\hline 
390
APQ\_Bigserial    &  -           &  N        &  BIGSERIAL\\
391
\hline 
392
APQ\_Boolean      &  Boolean     &  Y        &  BOOLEAN\\
393
\hline 
394
APQ\_Date         &  Ada.Calendar.Time & Y   &  DATE\\
395
\hline 
396
APQ\_Time         &  Ada.Calendar.Day\_Duration & Y & TIME\footnote{No timezone information}\\
397
\hline 
398
APQ\_Timestamp    &  Ada.Calendar.Time & N   & TIMESTAMP\footnote{No timezone information}\\
399
\hline 
400
APQ\_Timezone     &  Integer     &  N        &  range -23..23\\
401
\hline 
402
APQ\_Bitstring    &  -           &  N        &  BIT or BIT VARYING\\
403
\hline 
404
Decimal\_Type     &  -           &  -        &  PostgreSQL.Decimal\\
405
\hline 
406
range <>          &  -           &  -        &  Native Integers\\
407
\hline 
408
delta <>          &  -           &  -        &  Native Fixed Point\\
409
\hline 
410
digits <>         &  -           &  -        &  Native Floating Point\\
411
\hline 
412
delta <> digits <> & -           &  -        &  Native Decimal\\
413
\hline
414
\caption{PostgreSQL Data Types}\label{t:pqtypes}
415
\end{longtable}
416
417
The data type shown as ``Decimal\_Type''\index{Decimal\_Type}
418
is special, in that it is supported from a child package APQ\-.PostgreSQL\-.Decimal\index{APQ.PostgreSQL.Decimal}.
419
It represents a tagged\index{tagged type} type that provides an interface to the C routines\index{C routines}
420
used by the PostgreSQL database server, for arbitrary precision decimal\index{precision, arbitrary}
421
values.
422
423
424
\subsection{MySQL Data Types\label{MySQL Data Types}}
425
426
Table \ref{t:mytypes} summarizes the MySQL\index{data types, MySQL} specific data types and the
427
corresponding APQ data types.
428
429
\begin{longtable}{|l|c|c|l|}
430
\hline 
431
APQ Data Type        &  Ada Spec                   &  Subtype     &  Comments\\
432
\hline
433
\hline 
434
Row\_ID\_Type        &  unsigned 64 bits           &  N           &  For all databases\\
435
\hline 
436
APQ\_Smallint        &  signed 16 bits             &  N           &  SMALLINT\\
437
\hline 
438
APQ\_Integer         &  signed 32 bits             &  N           &  INTEGER\\
439
\hline 
440
APQ\_Bigint          &  signed 64 bits             &  N           &  BIGINT\\
441
\hline 
442
APQ\_Real            &  digits 6                   &  N           &  REAL\\
443
\hline 
444
APQ\_Double          &  digits 15                  &  N           &  DOUBLE PRECISION\\
445
\hline 
446
APQ\_Serial          &  range 1..2147483647        &  N           &  \emph{INTEGER}\\
447
\hline 
448
APQ\_Bigserial       &  range 1..2{*}{*}63         &  N           &  \emph{BIGINT}\\
449
\hline 
450
APQ\_Boolean         &  Boolean                    &  Y           &  BOOLEAN\\
451
\hline 
452
APQ\_Date            &  Ada.Calendar.Time          &  Y           &  DATE\\
453
\hline 
454
APQ\_Time            &  Ada.Calendar.Day\_Duration &  Y           &  TIME\\
455
\hline 
456
APQ\_Timestamp       &  Ada.Calendar.Time          &  N           &  TIMESTAMP\\
457
\hline 
458
APQ\_Timezone        &  range -23..23              &  N           &  \emph{Not in MySQL}\\
459
\hline 
460
APQ\_Bitstring       &  array(Positive) of APQ\_Boolean & N       &  \emph{Not in MySQL}\\
461
\hline
462
\caption{MySQL Data Types}\label{t:mytypes}
463
\end{longtable}
464
465
Notice the italicized SQL keywords\index{keywords, SQL} in the table. They identify the
466
SQL keywords that differ from PostgreSQL\index{PostgreSQL}. However, the programmer
467
only needs to be concerned with these SQL\index{keywords, SQL} keywords when creating new
468
tables or temporary tables. For example a column of type SERIAL\index{SERIAL} in
469
a PostgreSQL table, should be declared as a INTEGER\index{INTEGER} type in MySQL.
470
471
472
\section{Sybase Data Types}
473
474
The chart below outlines the mappings between APQ data types and Sybase
475
server data types\index{data types, Sybase}. The italicized SQL keywords
476
\index{keywords, SQL} in the table identify
477
the keywords that differ from PostgreSQL\index{PostgreSQL}. The following notes are
478
particular to Sybase\index{Sybase}:
479
480
\begin{itemize}	
481
   \item APQ\_Bigint is not completely range compatible with Sybase's \emph{NUMERIC}
482
         \index{APQ\_Bigint}\index{NUMERIC}\index{DECIMAL}
483
         (or \emph{DECIMAL}) server types. APQ\_Bigint will always accept Sybase server
484
         values, but the server will not be able to accept the full APQ\_Bigint range of values.
485
         To comply with the database server's range,
486
         the application designer should use:
487
\end{itemize}
488
489
\index{Sybase\_Bigint}
490
\begin{Code}
491
subtype Sybase_Bigint is APQ_Bigint
492
   range -10**38..10**38-1;
493
\end{Code}
494
495
\begin{itemize}
496
   \item APQ\_Bigserial\index{APQ\_Bigserial} is not supported.
497
   \item APQ\_Boolean\index{APQ\_Boolean}  maps to Sybase's data type \emph{BIT.}
498
   \item APQ\_Timezone\index{APQ\_Timezone} is not supported by any Sybase data type.
499
   \item APQ\_Bitstring\index{APQ\_Bitstring} is not supported.
500
\end{itemize}
501
502
Table \ref{t:sytypes} lists the APQ types supported for Sybase.
503
504
\begin{longtable}{|l|c|c|l|}
505
\hline 
506
APQ Data Type        &  Ada Spec          &  Subtype           &  Comments\\
507
\hline
508
\hline 
509
Row\_ID\_Type        &  unsigned 64 bits  &  N                 &  For all databases\\
510
\hline 
511
APQ\_Smallint        &  signed 16 bits    &  N                 &  SMALLINT\\
512
\hline 
513
APQ\_Integer         &  signed 32 bits    &  N                 &  INTEGER/INT\\
514
\hline 
515
APQ\_Bigint          &  signed 64 bits ($-10^{38}..$$10^{38}\textrm{-1}$) & N & \emph{NUMERIC/DECIMAL}\\
516
\hline 
517
APQ\_Real            &  digits 6          &  N                 &  REAL\\
518
\hline 
519
APQ\_Double          &  digits 15         &  N                 &  DOUBLE PRECISION\\
520
\hline 
521
APQ\_Serial          &  range 1..2147483647 & N                &  \emph{INTEGER}\\
522
\hline 
523
APQ\_Bigserial       &  range 1..$2^{63}$ &  N                 &  ???\\
524
\hline 
525
APQ\_Boolean         &  Boolean           &  Y                 &  \emph{BIT}\\
526
\hline 
527
APQ\_Date            &  Ada.Calendar.Time &  Y                 &  DATE\\
528
\hline 
529
APQ\_Time            &  Ada.Calendar.Day\_Duration & Y         &  TIME\\
530
\hline 
531
APQ\_Timestamp       &  Ada.Calendar.Time &  N                 &  \emph{DATETIME}\\
532
\hline 
533
APQ\_Timezone        &  range -23..23     &  N                 &  \emph{Not in Sybase}\\
534
\hline 
535
APQ\_Bitstring       &  array(Positive) of APQ\_Boolean & N    &  \emph{Not in Sybase}\\
536
\hline
537
\caption{Sybase Data Types}\label{t:sytypes}
538
\end{longtable}
539
540
541
\section{Database Objects\label{Database_Objects:Section}}
542
543
Much of the binding between Ada\index{Ada} and the database server is provided
544
through the use of tagged\index{tagged record} record types. Presently the APQ binding
545
operates through three object types\index{object types, APQ} listed in Table \ref{t:APQObj}.
546
547
\begin{table}
548
   \begin{center}
549
   \begin{tabular}{lll}
550
   Derived From            &  Object Type       &  Purpose\\
551
   \hline
552
   Root\_Connection\_Type  &  Connection\_Type  & Database connection\\
553
   Root\_Query\_Type       &  Query\_Type       & SQL interface\\
554
   N/A                     &  Blob\_Type        & Blob operations\\
555
   \end{tabular}
556
   \end{center}
557
   \caption{APQ Object Types}\label{t:APQObj}
558
\end{table}
559
560
The APQ objects from Table \ref{t:APQObj} are described more fully as follows:
561
562
\begin{description}
563
   \item[Connection\_Type] object is used with Query\_Type and Blob\_Type objects
564
         to perform SQL queries and blob operations respectively. This object
565
         maintains the connection to the database server.
566
   \item[Query\_Type] objects are used with one Connection\_Type object
567
         to perform SQL query operations. This object holds the text of the
568
         SQL query, some query state and result information. To execute a 
569
         query, it must be used in conjunction with a Connection\_Type object.
570
   \item[Blob\_Type] objects are used with one Connection\_Type object to 
571
         perform blob operations. This is currently only supported for PostgreSQL
572
         by APQ. All blob operations must occur within a transaction.
573
\end{description}
574
575
\begin{floatingtable}{
576
      \begin{tabular}{lc}
577
      Object            & Finalized \\
578
      \hline 
579
      Connection\_Type  & Yes \\
580
      Query\_Type       & Yes \\
581
      Blob\_Type        & No \\
582
      \end{tabular}}
583
\caption{Object Finalization Behavior}\label{t:Finalization}
584
\end{floatingtable}
585
586
Table \ref{t:Finalization} lists the three APQ objects and their finalization
587
behaviour.
588
While the Connection\_Type\index{Connection\_Type}
589
and Query\_Type\index{Query\_Type} objects are subject to
590
finalization, the Blob\_Type\index{Blob\_Type} is not.
591
This is because it represents an access type to
592
a Blob\_Object. This is similar in concept to an open a file, using
593
the File\_Type data type. This design approach was necessary
594
to support Ada\index{Ada} Streams\index{streams, Ada} oriented access for blobs.
595
596
\subsection{Object Hierarchy}
597
598
Before multiple database products were supported, the APQ object hierarchy\index{hierarchy}
599
was simple. To provide generic level support however, there are now
600
root\index{root objects} objects and derived objects\index{derived objects}. In most programming
601
contexts, the application writer does not need to be concerned with this fact.
602
However, if you frequently inspect the spec files\index{spec files} instead of the documentation\index{documentation},
603
you must be aware that primitives\index{primitives} for a given object may be declared
604
in multiple places. Examine Table \ref{t:pkghier} to review the APQ package hierarchy.
605
606
\begin{table}
607
   \begin{center}
608
      \begin{tabular}{ll}
609
         Package Name            & Description \\
610
         \hline 
611
         APQ                     & Root objects and primitives \\
612
         APQ.PostgreSQL          & Declarations and constants unique to PostgreSQL \\
613
         APQ.PostgreSQL.Client   & Derived objects and added primitives \\
614
         APQ.MySQL               & Declarations and constants unique to MySQL \\
615
         APQ.MySQL.Client        & Derived objects and added primitives \\
616
         APQ.Sybase              & Declarations and constants unique to Sybase \\
617
         APQ.Sybase.Client       & Derived objects and added primitves for Sybase \\
618
      \end{tabular}
619
   \end{center}
620
   \caption{APQ Package Hierarchy}\label{t:pkghier}
621
\end{table}
622
623
Table \ref{t:pkghier} illustrates that support for a given database is derived\index{derived}
624
from the APQ top level\index{top level package} package. Root objects\index{root level} are declared in APQ,
625
with common functionality. Some primitives must be overridden\index{overridden} by the
626
derived object in database specific packages. For example, APQ.Root\_Query\_Type
627
declares a primitive named Value (\emph{APQ.Value)} to return a string
628
column result. If this particular method is called, the exception
629
\emph{Is\_Abstract}\index{Is\_Abstract} will be raised to indicate that it must be overriden
630
with code to handle the specific database being used. Normally the
631
user would invoke APQ\-.MySQL\-.Client\-.Value when using the MySQL\index{MySQL} database,
632
for example. The programmer normally need not be aware of these details,
633
since object dispatching\index{dispatching} takes care of these details.
634
635
For this reason, the APQ\-.MySQL\-.Query\_Type object for example, is
636
derived from the APQ\-.Root\_Query\_Type\index{Root\_Query\_Type} object. This Query\_Type\index{Query\_Type} object
637
will provide its own implementation of the Value\index{Value} function to return
638
a column result, and will work as required.
639
640
Consequently, when looking for primitives\index{primitives} available to the Query\_Type
641
object, don't forget that many common primitives\index{common primitives} will be inherited\index{inherited}
642
from the APQ\-.Root\-\_Query\-\_Type object. The same is true for Connection\-\_Type\index{Connection\_Type}
643
objects. A number of common primitives are inherited from the APQ\-.Root\_Connection\_Type
644
object.
645
646
647
\chapter{Connecting to the Database}
648
649
Before any useful work can be accomplished by a database client program,
650
a connection must be established between the Ada program and the database
651
server. This chapter will demonstrate how to use the APQ binding\index{binding} to
652
enable a program to connect\index{connect} and disconnect\index{disconnect}
653
from the database server.
654
655
\section{The Connection\_Type}
656
657
The Connection\_Type\index{Connection\_Type} object holds everything that is needed to maintain
658
a connection\index{connection} to the database server. There are seven groups of primitive\index{primitive}
659
operations for this object:
660
661
\begin{enumerate}
662
   \item Context\index{Context} setting operations
663
   \item Connection\index{Connection} operations
664
   \item Connection Information functions\index{information functions}
665
   \item General Information operations
666
   \item Implicit operations (Finalization\index{Finalization})
667
   \item Trace Facilities\index{trace facilities}
668
   \item Generic Database Operations
669
\end{enumerate}
670
671
\section{Context Setting Operations}\label{Context_Setting_Operations}
672
673
These primitives ``configure''\index{configure} the connection\index{connection} that is
674
to be made later. When the object is initially created, it is in the
675
disconnected\index{disconnected state} state. While disconnected, configuration changes can be
676
made in to affect the next connection attempt. With the exception of the
677
database name\index{database name}, the application should not make configuration\index{configuration} changes
678
while the object is in the connected state\index{connected state}.
679
\footnote{This is not yet enforced by APQ.}
680
681
The configuration primitives\index{primitives} are listed in Table \ref{t:ctxops}.
682
\footnote{The items marked ``Root'' are primitives from APQ.Root\_Query\_Type.
683
The items marked {}``Derived'' are those overrides that are declared
684
on the APQ.{*}.Query\_Type object.}
685
686
\begin{table}
687
   \begin{center}
688
      \begin{tabular}{ccll}
689
      Type & Derivation & Name                  & Purpose \\
690
      \hline 
691
      proc & Root       & Set\_Host\_Name       & Set server host name \\
692
      proc & Root       & Set\_Host\_Address    & Set server host IP address \\
693
      proc & Root       & Set\_Port             & Set server port number \\
694
      proc & Root       & Set\_DB\_Name         & Set database name \\
695
      proc & Root       & Set\_User\_Password   & Set userid and password \\
696
      proc & Root       & Set\_Instance         & Set instance name to use \\
697
      proc & Root       & Set\_Options          & Set userid and password \\
698
      \end{tabular}
699
   \end{center}
700
\caption{Context Setting Primitives}\label{t:ctxops}
701
\end{table}
702
703
It would be nice if all database software products worked the same
704
way but the reality is very different. Table \ref{t:ctxdiffs} indicates how
705
the primitives apply by database product.\label{Set_Instance Support Chart}
706
In the table you can see that PostgreSQL\index{PostgreSQL} and MySQL\index{MySQL} establish their
707
connection by specifying the host, port and database name. Sybase
708
on the other hand, specifies this information in their \emph{interface}
709
file. To access the appropriate Sybase\index{Sybase interface entry} interface entry requires only
710
the \emph{instance}\index{instance} information supplied by the Set\_Instance\index{Set\_Instance} call.
711
712
\begin{table}
713
   \begin{center}
714
      \begin{tabular}{lccc}
715
      Primitive            & PostgreSQL   & MySQL  & Sybase \\
716
      \hline 
717
      Set\_Host\_Name      & Yes          & Yes    & Ignored \\
718
      Set\_Host\_Address   & Yes          & Yes    & Ignored \\
719
      Set\_Port            & Yes          & Yes    & Ignored \\
720
      Set\_DB\_Name        & Yes          & Yes    & See Note %
721
      \footnote{Set\_DB\_Name is useful after the connection is made.}\\
722
      Set\_User\_Password  & Yes          & Yes    & Yes \\
723
      Set\_Instance        & No           & No     & Yes \\
724
      Set\_Options         & Yes          & Yes    & Yes \\
725
      \end{tabular}
726
   \end{center}
727
\caption{Context Setting Differences}\label{t:ctxdiffs}
728
\end{table}
729
730
\subsection{PostgreSQL Defaults}
731
732
The PostgreSQL database defines certain environment\index{environment, PostgreSQL} variables that
733
can specify defaults. These and the fallback\index{fallback values} values are documented
734
in Table \ref{t:pqdef}.
735
736
\begin{table}
737
   \begin{center}
738
      \begin{tabular}{cclll}
739
      Type & Derivation    & Name               & Default      & Fallback \\
740
      \hline 
741
      proc & Root          & Set\_Host\_Name    & PGHOST       & localhost\\
742
      proc & Root          & Set\_Host\_Address & PGHOST       & localhost\\
743
      proc & Root          & Set\_Port          & PGPORT       & 5432\\
744
      proc & Root          & Set\_DB\_Name      & PGDATABASE   & LOGNAME\\
745
      proc & Root          & Set\_User\_Password &
746
         \begin{tabular}{l}
747
            PGUSER\\
748
            PGPASSWORD\\
749
         \end{tabular}
750
        & LOGNAME\\
751
      proc & Root          & Set\_Options       & PGOPTIONS    & ""\\
752
      \end{tabular}
753
   \end{center}
754
   \caption{PostgreSQL Context Defaults}\label{t:pqdef}
755
\end{table}
756
757
The capitalized names in the table for the ``Default'' and ``Fallback''
758
columns represent environment\index{environment} variable names.
759
When any of the environment\index{environment variables} variables are undefined in the ``Default''
760
column, the value used is determined by the ``Fallback'' value
761
listed. The fallback\index{fallback} variable name LOGNAME\index{LOGNAME}
762
is simply used to represent the current user's userid\index{userid}.%
763
\footnote{The PostgreSQL libpq library may in fact, completely ignore the LOGNAME
764
environment variable, and simply look up the userid in the /etc/password
765
file.%
766
} When no password\index{password} value is provided and no PGPASSWORD\index{PGPASSWORD}
767
environment variable exists, then no password is assumed.
768
769
770
\subsection{Procedure Set\_Host\_Name}
771
772
The Set\_Host\_Name\index{Set\_Host\_Name} procedure accepts the following arguments
773
774
\begin{Code}
775
procedure Set_Host_Name(
776
   C :         in out Connection_Type;
777
   Host_Name : in     String
778
);
779
\end{Code}
780
781
The following example configures the Connection\_Type object to connect
782
to host\index{host name} ``witherspoon'':
783
784
\begin{Example}
785
declare
786
   C : Connection_Type;
787
begin
788
   Set_Host_Name(C,"witherspoon");
789
\end{Example}
790
791
\begin{description}
792
\item [Note:]Sybase ignores this API call.
793
\end{description}
794
795
\subsection{Procedure Set\_Host\_Address}
796
797
The procedure takes two arguments, in the same fashion as Set\_Host\_Name\index{Set\_Host\_Address}:
798
799
\begin{Code}
800
procedure Set_Host_Address(
801
   C :            in out Connection_Type;
802
   Host_Address : in     String
803
);
804
\end{Code}
805
806
The following example configures the Connection\_Type object to connect
807
to IP address\index{IP address} 10.0.0.7:
808
809
\begin{Example}
810
declare
811
   C : Connection_Type;
812
begin
813
   Set_Host_Address(C,"10.0.0.7");
814
\end{Example}
815
816
\begin{description}
817
\item [Note:]Sybase ignores this API call.
818
\end{description}
819
820
\subsection{Procedure Set\_Port (IP)}
821
822
This procedure configures the port\index{port} where the database
823
server\index{server} is listening\index{listening} (when using TCP/IP\index{TCP/IP}
824
as the transport\index{transport}):
825
826
\begin{Code}
827
procedure Set_Port(
828
   C :           in out Connection_Type;
829
   Port_Number : in     Integer
830
);
831
\end{Code}
832
833
\begin{floatingtable}{
834
   \begin{tabular}{ccc}
835
   Database                &  Default  &  Port\\
836
   \hline 
837
   PostgreSQL              &  IP       &  5432\\
838
   MySQL                   &  UNIX     &  ?\\
839
   Sybase                  &  N/A      &  Ignored\\
840
   \end{tabular}}
841
   \caption{Default Database Connections}\label{t:defdb}
842
\end{floatingtable}
843
844
Table \ref{t:defdb} shows the connection defaults by database product. Some of these
845
are influenced by APQ. For example, APQ defaults to using a TCP/IP connection for the
846
PostgreSQL standard port of 5432.
847
848
The next example
849
shows how the port\index{port} number is configured.
850
The example configures APQ to use TCP/IP 
851
port number 5432\index{port 5432} to connect to
852
a PostgreSQL database.
853
854
\begin{Example}
855
declare
856
   C : Connection_Type;
857
begin
858
   Set_Port(C,5432);
859
\end{Example}
860
861
\begin{description}
862
\item [Note:]Sybase ignores this API call.
863
\end{description}
864
865
\subsection{Procedure Set\_Port (UNIX)}
866
867
To create a local UNIX socket connection to the database, there is
868
an overloaded version of Set\_Port\index{Set\_Port} that accepts a string\index{string} parameter
869
instead of an integer\index{port, integer} port number.
870
871
\begin{Code}
872
procedure Set_Port(
873
   C :           in out Connection_Type;
874
   Port_Number : in     String
875
);
876
\end{Code}
877
878
Specify a null string\index{null string} for the connection\index{connection} 
879
to use the local\index{local socket} UNIX\index{UNIX socket} socket default.
880
881
This parameter has changed somewhat as PostgreSQL\index{PostgreSQL} evolves. If you
882
are experiencing trouble getting a UNIX\index{UNIX socket} socket connection to work,
883
check the database documentation for PostgreSQL carefully. The following
884
example has been tested to work on PostgreSQL version 7.3.5.
885
886
\begin{Example}
887
declare
888
   C : Connection_Type;
889
begin
890
   Set_Port(C,"5432");
891
\end{Example}
892
893
See the troubleshooting chapter for tips.
894
895
\subsection{Procedure Set\_DB\_Name}
896
897
This procedure call configures the name of the database that the server
898
is to use \emph{prior} to the connection being established. Once
899
the connection has been established, calling Set\_DB\_Name\index{Set\_DB\_Name} switches the 
900
connection\index{connection} to use the named database.
901
The calling signature for this primitive is as follows:
902
903
\begin{Code}
904
procedure Set_DB_Name(
905
   C :       in out Connection_Type;
906
   DB_Name : in     String
907
);
908
\end{Code}
909
910
The following code fragment shows how the database name\index{database name} is configured
911
to be ``production'':
912
913
\begin{Example}
914
declare
915
   C : Connection_Type;
916
begin
917
   Set_DB_Name(C,"production");
918
\end{Example}
919
920
The Set\_DB\_Name \emph{always} acts as a configuration setting \emph{prior}
921
to connecting to the database server. Calling Set\_DB\_Name on a Connection\_Type\index{Connection\_Type}
922
object that has an open server connection to the database, can result
923
in hidden SQL commands for some databases.%
924
\footnote{For PostgreSQL and Sybase, a USE <database> command must be executed.%
925
} Table \ref{t:setdb} summarizes the behaviour according to database product.
926
927
\begin{table}
928
   \begin{center}
929
      \begin{tabular}{llll}
930
      Database Vendor   &  Before Connecting &  While Connecting           &  After Connected\\
931
      \hline 
932
      PostgreSQL        &  Configuration     &  uses config     &  ``USE'' Executed\\
933
      MySQL             &  Configuration     &  uses config.    &  MySQL Client Call\\
934
      Sybase            &  Pending SQL       &  ``USE'' executed   &  ``USE'' Executed\\
935
      \end{tabular}
936
   \end{center}
937
   \caption{Set\_DB\_Name Behaviour}\label{t:setdb}
938
\end{table}
939
940
From the table you can see that PostgreSQL\index{PostgreSQL} and MySQL\index{MySQL} configure the
941
database prior to connecting\index{connecting} (connecting also establishes the database
942
to be used). When Set\_\-DB\_\-Name is called after a connection has been
943
established, the database server will switch\index{switch database} to the requested database.
944
For some databases, this happens through the native\index{native client API} client API library\index{library}
945
(MySQL), but for others, a ``USE~<database>''\index{USE database} SQL\index{SQL} command must
946
be executed (internally within APQ).
947
948
\begin{floatingtable}{
949
   \begin{tabular}{ll}
950
   Exception Name    &  Reason\\
951
   \hline 
952
   Use\_Error        &  Unsuccessful doing a ``USE <database>''\\
953
   \end{tabular}}
954
   \caption{Set\_DB\_Name Exceptions}\label{t:sdbx}
955
\end{floatingtable}
956
957
Sybase\index{Sybase} is different again, because does not establish the database
958
at connect time\index{connect time} (Sybase will use the configured default database).
959
So a call to Set\_DB\_Name will queue a ``USE <database>''\index{USE database} SQL\index{SQL}
960
statement, to be executed by APQ, once the connection succeeds. If
961
another Set\_DB\_Name is performed while connected, new ``USE <database>''
962
SQL statements are executed on the Sybase server\index{Sybase server} connection provided.
963
964
The exceptions listed in Table \ref{t:sdbx}\index{exception} are possible when
965
using a new database name.
966
967
The case of the database name used is affected according to the case policy\index{case policy}
968
that is in effect for the connection\index{connection}. This is summarized in Table \ref{t:cpol}
969
for each database vendor product.
970
971
\begin{table}
972
   \begin{center}
973
      \begin{tabular}{llll}
974
      Database Product  &  Case Policy          &  Effect on DB\_Name      &  DB Name Sensitive\\
975
      \hline 
976
      PostgreSQL        &  Ignored              &  Case preserved          &  Yes\\
977
      MySQL             &  Ignored              &  Case preserved          &  Yes\\
978
      Sybase            &  Ignored              &  Case preserved          &  Yes\\
979
      \end{tabular}
980
   \end{center}
981
   \caption{Case Policy by Product}\label{t:cpol}
982
\end{table}
983
984
\subsection{Procedure Set\_User\_Password}
985
986
This procedure call configures both the userid\index{userid} and the password\index{password} together.
987
If there is no password, then supply the null string\index{null string}:
988
989
\begin{Code}
990
procedure Set_User_Password(
991
   C :             in out Connection_Type;
992
   User_Name :     in     String;
993
   User_Password : in     String
994
);
995
\end{Code}
996
997
The following code fragment illustrates how the userid and
998
password is configured:
999
1000
\begin{Example}
1001
declare
1002
   C :   Connection_Type;
1003
begin
1004
   Set_User_Password(C,"myuserid","xyzzy");
1005
\end{Example}
1006
1007
\subsection{Procedure Set\_Case}
1008
1009
One of the goals of APQ was to make writing of portable database\index{portable database code} code
1010
possible. While this isn't completely possible, the goal remains to
1011
reduce database differences. Until the introduction of Sybase\index{Sybase} within
1012
APQ, there was little concern for the case of SQL query\index{SQL query code} code used. 
1013
1014
This APQ manual has always used examples where SQL code is uppercased\index{uppercased SQL code},
1015
with Ada\index{Ada} code using normal Ada95\index{Ada95} conventions. This helps to make the
1016
SQ\index{SQL}L code standout, and separate it from the other code. Sybase introduces
1017
a problem however, since the Sybase server is case sensitive\index{case sensitive} when
1018
referring to tables\index{tables} and column\index{column names} names. This feature cannot be disabled
1019
for a Sybase server%
1020
\footnote{MySQL databases can be configured to be caseless or case sensitive.%
1021
}. Since users of Sybase\index{Sybase} tend to use lowercase\index{lowercase names} names, this creates
1022
a bit of a problem for portable\index{portable SQL} SQL text within APQ.
1023
1024
The approach that APQ 2.2 uses for Sybase\index{Sybase} (and future databases where
1025
this matters), all SQL\index{SQL} code is changed to lowercase\index{lowercase} before being
1026
sent to the server. Before the reader panics thinking that this won't
1027
work, it should be made clear that APQ does not change the case\index{case of SQL} of
1028
any string\index{string} that is quoted\index{quoted} (using the Append\_Quoted\index{Append\_Quoted} functions for
1029
example). A WHERE\index{WHERE clause} clause such as the following will preserve the text
1030
within quotes\index{quotes}:
1031
1032
\begin{SQL}
1033
1034
   where part_no = "XZ98-307"
1035
1036
\end{SQL}
1037
1038
APQ keeps track of what parts of the SQL\index{SQL query} query were quoted\index{quoted} and which
1039
parts were not. This is \emph{not} done by parsing\index{parsing} the SQL text. That
1040
would be prone to error and would require intimate knowledge of every
1041
SQL dialect supported in APQ. Instead, the string\index{string} fragments are marked
1042
for ``preserve''\index{preserve case} case or ``not preserve''\index{preserved, not} as the Query\_Type\index{Query\_Type}
1043
object collects text. When the full SQL text\index{SQL text} is require by a routine
1044
like To\_String\index{To\_String}, then the standing case policy\index{case policy} is applied to each
1045
string\index{string fragment} fragment that has ``not preserve''\index{preserved, not}.
1046
1047
You can change this APQ case policy\index{case policy} for Sybase (or any other database).
1048
The Set\_Case\index{Set\_Case} function gives you complete control over what the policy
1049
to use for SQL case\index{SQL case}. You can choose one of the SQL\_Case\_Type\label{SQL_Case_Type Choices}
1050
\index{SQL\_Case\_Type} options, which are listed in Table~\ref{t:cpolicies}.
1051
1052
\begin{table}
1053
   \begin{center}
1054
      \begin{tabular}{ll}
1055
         Case Policy    &  Description\\
1056
         \hline 
1057
         Preserve\_Case &  Do not make any case changes to the SQL text\\
1058
         Lower\_Case    &  Force unquoted SQL text to lowercase\\
1059
         Upper\_Case    &  Force unquoted SQL text to uppercase\\
1060
      \end{tabular}
1061
   \end{center}
1062
   \caption{Case Policies for SQL Text}\label{t:cpolicies}
1063
\end{table}
1064
1065
\begin{floatingtable}{
1066
   \begin{tabular}{ll}
1067
   Database       &  Default SQL Case Policy\\
1068
   \hline 
1069
   PostgreSQL     &  Upper\_Case\\
1070
   MySQL          &  Lower\_Case\\
1071
   Sybase         &  Lower\_Case\\
1072
   \end{tabular}}
1073
\caption{Default Case Policies}\label{t:dfcpol}
1074
\end{floatingtable}
1075
1076
Table~\ref{t:dfcpol} summarizes the default case policies\index{case policies} used in APQ 2.2
1077
for the different database vendor products supported.
1078
1079
MySQL\index{MySQL} joins Sybase\index{Sybase} in this case policy because by default, MySQL is
1080
case sensitive. If you have configured your MySQL server to be case
1081
insenstive, then any setting will do (Upper\_Case\index{Upper\_Case} is suggested for
1082
the benefit of the trace log displays). Most users of Sybase\index{Sybase} will
1083
likely prefer either the Lower\_Case\index{Lower\_Case} or Preserve\_Case\index{Preserve\_Case}
1084
policies instead.
1085
1086
The Set\_Case\index{Set\_Case} API procedure for the Connection\_Type object is defined
1087
as follows:
1088
1089
\begin{Code}
1090
procedure Set_Case(
1091
   C :        in out Connection_Type;
1092
   SQL_Case : in     SQL_Case_Type
1093
);
1094
\end{Code}
1095
1096
You may also use the Get\_Case\index{Get\_Case} function primitive to find out what
1097
the current policy in effect is. Please note that a change in policy
1098
only affects the outcome of the next call to the following
1099
pimitives of the Query\_Type\index{Query\_Type} object:
1100
1101
\begin{itemize}
1102
   \item To\_String
1103
   \item Execute
1104
   \item Execute\_Checked
1105
\end{itemize}
1106
1107
The Set\_Case\index{Set\_Case} call will not actually change the SQL text\index{SQL text} stored within
1108
the Query\_Type object. It only sets the policy\index{case policy} mode.
1109
1110
The following example shows how to undo the Sybase default of lowercasing
1111
the SQL text:
1112
1113
\begin{Example}
1114
declare
1115
   C : Connection_Type;
1116
   Q : Query_Type;
1117
begin
1118
   ...
1119
   Set_Case(C,Preserve_Case);
1120
   ...
1121
   Append(Q,"from table Mixed_Case");
1122
   Execute(Q,C); -- SQL case is preserved here
1123
\end{Example}
1124
1125
\subsubsection{The Viral Nature of Connection\_Type}
1126
1127
Note that APQ does permit altering the case policy\index{case policy} for Query\_Type\index{Query\_Type}
1128
objects in addition to the Connection\_Type\index{Connection\_Type} object being described
1129
here. It should be noted however, that the setting held by the Connection\_Type
1130
is viral\index{viral nature} in nature. Whenever a Query\_Type object is used in conjunction
1131
with a Connection\_Type object, in a \emph{Execute}\index{Execute} 
1132
or \emph{Execute\_Checked}\index{Execute\_Checked}
1133
call for example, the Query\_Type object will inherit the setting
1134
held by the corresponding Connection\_Type object. For this reason,
1135
the best application practice is to establish your application case
1136
policy\index{case policy} in all Connection\_Type objects used by your application. It
1137
is also best practice to use one Connection\_Type object wherever
1138
possible, since many queries can share one connection\index{shared connection}.
1139
1140
The only reason you should consider applying a case policy\index{case policy} directly
1141
to a Query\_Object, is perhaps for application specific uses of the
1142
SQL text\index{SQL text}. For example, you could build a query\index{query, build a} in a Query\_Type object,
1143
set the case policy to Upper\_Case\index{Upper\_Case}, and then use the To\_String\index{To\_String} function
1144
primitive to extract out the SQL text for logging\index{logging} or user display\index{display}
1145
purposes. Once however the Query\_Type is used with a Connection\_Type
1146
however, (in \emph{Execute}) the Connection\_Type's setting will not
1147
only prevail for the primitive, but will also force the Query\_Type's
1148
policy to agree upon return from the call.
1149
1150
1151
\subsection{Procedure Set\_Options\label{Procedure Set_Options}}
1152
1153
This procedure call permits the caller to specify any specialized
1154
database server options. The options are specified in string form
1155
with this API call. The specific options, and the format\index{format} of those
1156
options\index{options} will vary according to the database being used. See the following
1157
subsections for additional information about the database engine\index{engine, database} specifics.
1158
1159
The procedure Set\_Options\index{Set\_Options} is documented as follows:
1160
1161
\begin{Code}
1162
procedure Set_Options(
1163
   C :       in out Connection_Type;
1164
   Options : in     String
1165
);
1166
\end{Code}
1167
1168
Exceptions\index{exceptions} can be raised if the options are being set on a connection
1169
that is already connected. Table \ref{t:soopts} lists the exceptions that may be
1170
raised by Set\_Options.
1171
1172
\begin{table}
1173
   \begin{center}
1174
      \begin{tabular}{ll}
1175
      Exception Name    &  Reason\\
1176
      \hline 
1177
      Failed            &  The option is either unsupported or setting was rejected\\
1178
      \end{tabular}
1179
   \end{center}
1180
   \caption{Set\_Options Exceptions}\label{t:soopts}
1181
\end{table}
1182
1183
If the options are configured for an unconnected\index{unconnected} Connection\_Type
1184
object, the exceptions if any, will be raised at the time of connection
1185
(See the Connect primitive).
1186
1187
The following PostgreSQL\index{PostgreSQL} code fragment illustrates how two options\index{options}
1188
may be configured:
1189
1190
\begin{Example}
1191
declare
1192
   C : Connection_Type;
1193
begin
1194
   Set_Options(C,"requiressl=1 dbname=test");
1195
\end{Example}
1196
1197
Note that in this example, the option string has been used to declare
1198
the database name to be used. Standard values should be set through
1199
the primitive functions provided (ie. use Set\_DB\_Name\index{Set\_DB\_Name} instead).
1200
Otherwise, when information primitives are added, you may not get
1201
correct results. Any non-standard options like the ``requiressl''\index{requiressl}
1202
option, should be configured as shown in this procedure call.
1203
1204
MySQL\index{MySQL} and Sybase\index{Sybase}, use a comma delimited list\index{delimited list} of options\index{options}.
1205
The following example shows how to get Sybase I/O\index{statistics, Sybase I/O} 
1206
and time statistics\index{statistics, time} recorded in your APQ trace\index{trace log} log:
1207
1208
\begin{Example}
1209
declare
1210
  C : Connection_Type;
1211
begin
1212
   Set_Options(C,"STATS_IO=TRUE,STATS_TIME=TRUE");
1213
\end{Example}
1214
1215
Option parsing\index{parsing} is rather limited. Everything between the '=' sign
1216
and the next comma is the value for the parameter. Different database
1217
products will use different parameter types\index{paramater types}. For example, MySQL\index{MySQL} will
1218
use 0 to represent False\index{false}, and 1 to represent True\index{true}. For Sybase\index{Sybase}, use
1219
F or False, and T or True for Boolean\index{Boolean} values.
1220
1221
1222
\subsubsection{PostgreSQL Options}
1223
1224
The documentation is not very clear about the format\index{format} of these options,
1225
but it appears that keyword=value\index{keyword value pairs}  pairs\index{keyword=value pairs}
1226
separated by \emph{spaces} for multiple options\index{options} are
1227
accepted. If you must include spaces or other special characters within
1228
the value component, then you must follow PostgreSQL\index{PostgreSQL} escaping rules\index{escaping rules}.
1229
Refer to the database server documentation for these details.
1230
1231
1232
\subsubsection{MySQL Options}
1233
1234
MySQL's\index{MySQL} C interface\index{C interface} is much different than PostgreSQL's C interface
1235
for options. MySQL uses an enumerated value\index{enumerated value} and argument pair\index{argument pair} when
1236
setting an option\index{option}.%
1237
\footnote{Although, some options do not use the argument.%
1238
} To keep the APQ interface friendly and consistent, APQ will accept
1239
all options and arguments in a string\index{string} form as documented in
1240
\Ref{Procedure Set_Options}. However, these string options\index{string options} must be
1241
processed by APQ and digested into arguments usable by the MySQL C
1242
client interface. Consequently, APQ must anticipate these options
1243
and the option format in advance. For these reasons, the MySQL options
1244
and their arguments will be partially documented here.
1245
1246
The format\index{format of option string} of the option string should be one or more option names
1247
and arguments, separated by commas. Option names\index{option names} are treated as caseless\index{caseless}
1248
(internally upcased\index{upcased}).
1249
1250
\begin{Example}
1251
1252
   Set\_Options(C,"CONNECT_TIMEOUT=3,COMPRESS,LOCAL_INFIL=1");
1253
1254
\end{Example}
1255
1256
Each option should be separated by a comma. APQ processes each option
1257
in left to right fashion, making multiple MySQL C API calls for each
1258
one. Table~\ref{t:myopts} lists the APQ supported options for MySQL.
1259
1260
\begin{table}
1261
   \begin{center}
1262
      \begin{tabular}{lll}
1263
         Option Name          &  Argument Type           &  Comments\\
1264
         \hline 
1265
         CONNECT\_TIMEOUT     &  Unsigned                &  Seconds\\
1266
         COMPRESS             &  None                    &  Compressed comm link\\
1267
         NAMED\_PIPE          &  None                    &  Windows: use a named pipe\\
1268
         INIT\_COMMAND        &  String                  &  Initialization command\\
1269
         READ\_DEFAULT\_FILE  &  String                  &  See MySQL\\
1270
         READ\_DEFAULT\_GROUP &  String                  &  See MySQL\\
1271
         SET\_CHARSET\_DIR    &  String                  &  See MySQL\\
1272
         SET\_CHARSET\_NAME   &  String                  &  See MySQL\\
1273
         LOCAL\_INFIL         &  Boolean                 &  See MySQL\\
1274
      \end{tabular}
1275
   \end{center}
1276
   \caption{MySQL Options}\label{t:myopts}
1277
\end{table}
1278
1279
It is important to observe that any option that requires an argument\index{argument, option},
1280
must have one. Any argument that requires an unsigned integer\index{unsigned}, must
1281
have an unsigned integer (otherwise an exception\index{exception} is raised). A MySQL\index{MySQL}
1282
Boolean\index{Boolean} argument should be the value 0 or 1. At the present time,
1283
APQ gathers string\index{string} data up until the next comma or the end of the
1284
string. Currently an option argument string cannot contain a comma
1285
character.
1286
\footnote{This needs to be corrected in a future release of APQ.}
1287
1288
1289
\subsubsection{Sybase Options}
1290
1291
Sybase documents several options\index{options, Sybase} in their ``Open Client C Programmer's
1292
Reference'' manual. All documented options are made available to
1293
the APQ developer, although some options are not recommended. 
1294
1295
\begin{floatingtable}{
1296
   \begin{tabular}{ll}
1297
   Option Value   &  Meaning\\
1298
   \hline 
1299
   TRUE           &  True\\
1300
   T              &  True\\
1301
   FALSE          &  False\\
1302
   F              &  False\\
1303
   \end{tabular}}
1304
   \caption{Boolean Option Values}\label{t:boolarg}
1305
\end{floatingtable}
1306
1307
Each Sybase option value must conform to certain data type format\index{format, option}
1308
and/or restrictions. Table~\ref{t:boolarg} lists
1309
acceptable argument values for Boolean\index{Boolean} options, within APQ. The
1310
case is not significant, but uppercase is recommended to make it stand out from
1311
the surrounding Ada code.
1312
1313
The following is an example of a Boolean option setting for the Sybase option STATS\_IO:
1314
1315
\begin{Example}
1316
1317
   "STATS_IO=TRUE"
1318
1319
\end{Example}
1320
1321
Some Sybase options require an integer\index{unsigned integer} (actually unsigned). Those
1322
options listed in the option table\index{option table} as requiring an Unsigned value,
1323
should be simply an unsigned value. The following is an example:
1324
1325
\begin{Example}
1326
1327
   "ROWCOUNT=1"
1328
1329
\end{Example}
1330
1331
String value arguments\index{string value arguments} are simply textual values that are placed between
1332
the equal sign and the next comma (or end of string). The following
1333
example illustrates:
1334
1335
\begin{Example}
1336
1337
   "AUTHOFF=sa"
1338
1339
\end{Example}
1340
1341
Some options are identified as taking ``String/NULL''. These options
1342
will take normal string values or simply the word NULL\index{NULL options}. The value
1343
NULL allows the system default to be used. The following is an example:
1344
1345
\begin{Example}
1346
1347
   "CHARSET=NULL"
1348
1349
\end{Example}
1350
1351
\begin{table}
1352
   \begin{center}
1353
      \begin{tabular}{ll}
1354
         Value             &  Sybase Option\\
1355
         \hline 
1356
         SUNDAY            &  CS\_OPT\_SUNDAY\\
1357
         MONDAY            &  CS\_OPT\_MONDAY\\
1358
         TUESDAY           &  CS\_OPT\_TUESDAY\\
1359
         WEDNESDAY         &  CS\_OPT\_WEDNESDAY\\
1360
         THURSDAY          &  CS\_OPT\_THURSDAY\\
1361
         FRIDAY            &  CS\_OPT\_FRIDAY\\
1362
         SATURDAY          &  CS\_OPT\_SATURDAY\\
1363
      \end{tabular}
1364
   \end{center}
1365
   \caption{Weekday Option Argument Values}\label{t:wkday}
1366
\end{table}
1367
1368
The DATEFIRST option\index{DATEFIRST option} accepts an argument Weekday argument. The valid
1369
range of values are listed in Table~\ref{t:wkday}.
1370
1371
The following example shows how the DATEFIRST option is used:
1372
1373
\begin{Example}
1374
1375
   "DATEFIRST=SUNDAY"
1376
1377
\end{Example}
1378
1379
\begin{table}
1380
   \begin{center}
1381
      \begin{tabular}{ll}
1382
      Value    &  Sybase Option\\
1383
      \hline 
1384
      MDY      &  CS\_OPT\_FMTMDY\\
1385
      DMY      &  CS\_OPT\_FMTDMY\\
1386
      YMD      &  CS\_OPT\_FMTYMD\\
1387
      YDM      &  CS\_OPT\_FMTYDM\\
1388
      MYD      &  CS\_OPT\_FMTMYD\\
1389
      DYM      &  CS\_OPT\_FMTDYM\\
1390
      \end{tabular}
1391
   \end{center}
1392
   \caption{Date Format Argument Values}\label{t:dtfmt}
1393
\end{table}
1394
1395
One last category of Sybase option arguments is the DATEFORMAT argument\index{DATEFORMAT option}
1396
type. The valid list of values for this type of argument are given in Table~\ref{t:dtfmt}.
1397
1398
The following is an example of such an option:
1399
1400
\begin{Example}
1401
1402
   "DATEFORMAT=YMD"
1403
1404
\end{Example}
1405
1406
Table~\ref{t:syonames} lists all of the options that APQ is able to recognize for Sybase.
1407
Each of the option names\index{option names} listed is equivalent to the 
1408
Sybase C macro\index{C macro, Sybase}
1409
constant if the prefix CS\_OPT\_\index{CS\_OPT\_{*}} is added to the option name. Consult
1410
the Sybase documentation for descriptions of the purpose of these
1411
options and when to apply them.
1412
1413
\begin{longtable}{lll}
1414
Option Name       &  Data Type            &  Notes\\
1415
\hline 
1416
ANSINULL          &  Boolean              &\\
1417
ANSIPERM          &  Boolean              &\\
1418
ARITHABORT        &  Boolean              &\\
1419
ARITHIGNORE       &  Boolean              &\\
1420
AUTHOFF           &  String               &\\
1421
AUTHON            &  String               &\\
1422
CHAINXACTS        &  Boolean              &\\
1423
CHARSET           &  String/NULL          &  Use NULL for default\\
1424
CURCLOSEONXACT    &  Boolean              &\\
1425
DATEFIRST         &  Weekday              &\\
1426
DATEFORMAT        &  YMD/MDY/etc.         &  May interfere with APQ\\
1427
FIPSFLAG          &  Boolean              &\\
1428
FORCEPLAN         &  Boolean              &\\
1429
FORMATONLY        &  Boolean              &\\
1430
GETDATA           &  Boolean              &\\
1431
IDENTITYOFF       &  String               &\\
1432
IDENTITYON        &  String               &\\
1433
IDENTITYUPD\_OFF  &  String               &\\
1434
IDENTITYUPD\_ON   &  String               &\\
1435
ISOLATION         &  Unsigned             &  0, 1 or 3\\
1436
NATLANG           &  String/NULL          &  Use NULL for default\\
1437
NOCOUNT           &  Boolean              &\\
1438
NOEXEC            &  Boolean              &\\
1439
PARSEONLY         &  Boolean              &\\
1440
QUOTED\_IDENT     &  Boolean              &\\
1441
RESTREES          &  Boolean              &\\
1442
ROWCOUNT          &  Unsigned             &\\
1443
SHOWPLAN          &  Boolean              &  Use at your own risk\\
1444
STATS\_IO         &  Boolean              &\\
1445
STATS\_TIME       &  Boolean              &\\
1446
STR\_RTRUNC       &  Boolean              &\\
1447
TEXTSIZE          &  Unsigned             &\\
1448
TRUNCIGNORE       &  Boolean              &\\
1449
\caption{Sybase Option Names}\label{t:syonames}
1450
\end{longtable}
1451
1452
Keep in mind that not all option settings will be compatible for use
1453
with APQ. Changing server date formats\index{date formats} to anything other than year-month-day
1454
format, is likely to cause problems within APQ, for example.
1455
1456
1457
\subsection{Procedure Set\_Notice\_Proc}
1458
1459
The PostgreSQL\index{PostgreSQL} database
1460
\footnote{The Set\_Notice\_Proc procedure is not available with MySQL.}
1461
server sends notice\index{notice messages} messages back to the libpq\index{libpq} C library\index{library}, that the
1462
APQ binding uses. These are received by a callback\index{callback}, after certain
1463
database operations have been completed. While the messages are saved
1464
in the Connection\_Type object (see also \Ref{Function Notice_Message}),
1465
they overwrite each other as each new message comes in. For this reason,
1466
it may be desireable for some applications to also receive a callback,
1467
so that they can process the messages without losing them. The most
1468
common reason to do this is to simply display them on standard error\index{standard error}.
1469
1470
The callback\index{callback}\index{Set\_Notice\_Proc} procedure must be defined as follows:
1471
\marginpar{The default setting for any new Connection\_Type object is No\_Notify.}
1472
1473
\begin{Code}
1474
procedure Notice_Callback(
1475
   C :       in out Connection_Type;
1476
   Message : in     String
1477
);
1478
\end{Code}
1479
1480
The Set\_Notice\_Proc takes an argument named Notify\_Proc\index{Notify\_Proc} that is
1481
of the following type:
1482
1483
\begin{Code}
1484
type Notify_Proc_Type is access
1485
   procedure(
1486
      C :       in out Connection_Type;
1487
      Message : in     String
1488
   );
1489
\end{Code}
1490
1491
Finally, the Set\_Notice\_Proc procedure has the following calling signature:
1492
\marginpar{Note that the Reset or Disconnect call will clear any
1493
registered Notify procedure.}
1494
1495
\begin{Code}
1496
procedure Set_Notice_Proc(
1497
   C :           in out Connection_Type;
1498
   Notify_Proc : in     Notify_Proc_Type
1499
);
1500
\end{Code}
1501
1502
This call can be made at any time to change the Notify\index{notify procedure} procedure.
1503
The object may or may not be connected\index{connected}. The new procedure takes effect
1504
immediately upon return, and will be used when the object is connected.
1505
The present implementation only maintains one such procedure.%
1506
\footnote{Note that the replaced procedure is not returned. A future implementation
1507
of APQ may address this.%
1508
}
1509
1510
1511
\subsubsection{Disabling Notify}
1512
1513
The APQ\-.PostgreSQL\-.Client\index{APQ\-.PostgreSQL\-.Client} package 
1514
provides the special constant No\_Notify\index{No\_Notify}
1515
for the application programmer to use. An example of disabling notification\index{disabling notification}
1516
follows:
1517
1518
\begin{Example}
1519
declare
1520
   C : Connection_Type;
1521
begin
1522
   ...
1523
   -- Enable notify processing
1524
   Set_Notify_Proc(C,My_Notify'Access);
1525
   ...
1526
   -- Disable notification
1527
   Set_Notify_Proc(C,No_Notify);
1528
\end{Example}
1529
1530
\subsubsection{Using Standard\_Error\_Notify}
1531
1532
During the debugging\index{debugging} phase of a database application, it may be useful
1533
to simply have the notice messages\index{notice messages} printed on Standard\_Error\index{Standard\_Error}. To
1534
do this, simply provide the access constant Standard\_Error\_Notify\index{Standard\_Error\_Notify}
1535
as the second argument:
1536
1537
\begin{Example}
1538
declare
1539
   C : Connection_Type;
1540
begin
1541
   ...
1542
   -- Send notices to stderr
1543
   Set_Notify_Proc(C,Standard_Error_Notify);
1544
   ...
1545
\end{Example}
1546
1547
\section{Connection Operations}
1548
1549
The APQ binding provides three primitives for connecting\index{connecting} and disconnecting\index{disconnecting}
1550
from the database server. They are summarized in Table~\ref{t:conprims}.
1551
1552
\begin{table}
1553
   \begin{center}
1554
      \begin{tabular}{lll}
1555
         Type     &  Name              &  Purpose\\
1556
         \hline
1557
         proc     &  Connect           &  Connect to the database server\\
1558
         proc     &  Disconnect        &  Disconnect from the database server\\
1559
         proc     &  Reset             &  Disconnect if connected\\
1560
      \end{tabular}
1561
   \end{center}
1562
   \caption{APQ Connection Primitives}\label{t:conprims}
1563
\end{table}
1564
1565
\subsection{Procedure Connect}
1566
1567
This primitive initiates a connection attempt with the database server
1568
as configured by the \Ref{Context_Setting_Operations} primitives.
1569
If the connection succeeds, the procedure call returns\index{Connect}
1570
successfully, leaving the Connection\_Type object in a connected state.
1571
1572
1573
\begin{Code}
1574
procedure Connect(
1575
   C : in out Connection_Type
1576
);
1577
\end{Code}
1578
1579
\begin{table}
1580
   \begin{center}
1581
      \begin{tabular}{ll}
1582
         Exception Name       &  Reason\\
1583
         \hline 
1584
         Not\_Connected       &  The connection attempt failed\\
1585
         Already\_Connected   &  There is already a connection\\
1586
         Failed               &  One or more configured options failed\\
1587
         Use\_Error           &  Connection OK, but USE database failed\\
1588
      \end{tabular}
1589
   \end{center}
1590
   \caption{Connect Exceptions}\label{t:conx}
1591
\end{table}
1592
1593
Table~\ref{t:conx} summarizes the exceptions that Connect may raise.
1594
1595
The Already\_Connected\index{Already\_Connected} exception indicates that you need to disconnect
1596
first, or use another Connection\_Type object if you are maintaining
1597
multiple connections\index{connections, multiple}. Failed will be raised if a pending option setting
1598
is unsupported or its setting has been rejected. The exception Use\_Error\index{Use\_Error}
1599
indicates that the connection itself succeeded, but the selection
1600
of the database failed. The connection will be returned in an unconnected\index{unconnected}
1601
state when Use\_Error is raised.
1602
1603
\begin{description}
1604
   \item[PostgreSQL Note:] \index{PostgreSQL}The Connect primitive as of APQ 1.91 automatically executes a 'SET
1605
      DATESTYLE TO ISO' \index{ISO}\index{DATESTYLE} command to guarantee that the APQ date routines
1606
      will function correctly, even when the PGDATESTYLE\index{PGDATESTYLE} environment variable
1607
      may choose something other than ISO. This implies however, that APQ
1608
      applications should always format date information in the ISO format.
1609
   \item[MySQL Note:]When MySQL\index{MySQL} returns dates in YYYYMMDD\index{YYYYMMDD} format, APQ
1610
      will automatically make the necessary adjustment, based upon the length
1611
      of the result.
1612
\end{description}
1613
1614
The following is an example call:
1615
1616
\begin{Example}
1617
declare
1618
   C : Connection_Type;
1619
begin
1620
   ...
1621
   begin
1622
      Connect(C);
1623
   exception
1624
      when No_Connection =>
1625
         -- Handle connection failure
1626
      when Already_Connected =>
1627
         ...; -- Indicates program logic problem
1628
      when others =>
1629
         raise;
1630
   end;
1631
\end{Example}
1632
1633
\subsection{Connection Cloning\label{Connection Cloning}}
1634
1635
Application writers may want additional connections cloned\index{cloning connections} from a
1636
given connection. A web server may want to do this for example. This
1637
could be performed by obtaining all of the connection information
1638
from the given connection and then proceed to configure a new connection,
1639
but this is tedious and error prone. To clone a new connection from
1640
an existing connection, simply use the Connect\index{Connect} primitive with the
1641
following calling signature (argument Same\_As is added):
1642
1643
\begin{Code}
1644
procedure Connect(
1645
   C :       in out Connection_Type;
1646
   Same_As : in     Connection_Type
1647
);
1648
\end{Code}
1649
1650
This primitive configures object C to use the same parameters as object
1651
Same\_As\index{Same\_As}. It then creates a connection to the database using these cloned\index{cloned}
1652
parameters. The exceptions that may be raised are listed in Table~\ref{t:cclonx}.
1653
1654
\begin{table}
1655
   \begin{center}
1656
      \begin{tabular}{ll}
1657
         Exception Name       &  Reason\\
1658
         \hline 
1659
         Not\_Connected       &  The connection attempt failed\\
1660
         Already\_Connected   &  There is already a connection\\
1661
      \end{tabular}
1662
   \end{center}
1663
   \caption{Connection Cloning Exceptions}\label{t:cclonx}
1664
\end{table}
1665
1666
The Not\_Connected\index{Not\_Connected} exception can be raised if the Same\_As connection
1667
is not connected (it must be connected). This same exception can be
1668
raised if the new connection fails (this should rarely happen unless
1669
your database is suddenly taken down or a network failure occurs).
1670
The Already\_Connected\index{Already\_Connected} exception is raised if \emph{C} is already
1671
connected.
1672
1673
\begin{description}
1674
   \item[Note:] Note that the trace settings of the Same\_As object are not
1675
      carried to the new object C. You must manually configure any trace
1676
      settings you require in the newly connected object C.
1677
\end{description}
1678
1679
The following example shows how a procedure My\_Subr can clone
1680
a new connection:
1681
1682
\begin{Example}
1683
procedure My_Subr(C : Connection_Type) is
1684
   C2 : Connection_Type;
1685
begin
1686
   Connect(C2,C); -- Clone a connection
1687
\end{Example}
1688
1689
\subsection{Procedure Disconnect}
1690
1691
The Disconnect\index{Disconnect} primitive closes the connection that was previously
1692
established in the Connection\_Type\index{Connection\_Type} object. The Disconnect primitive
1693
uses the following arguments:
1694
1695
\begin{Code}
1696
procedure Disconnect(
1697
   C : in out Connection_Type
1698
);
1699
\end{Code}
1700
1701
The list of possible exceptions for Disconnect are illustrated in Table~\ref{t:dconx}.
1702
1703
\begin{table}
1704
   \begin{center}
1705
      \begin{tabular}{ll}
1706
         Exception Name       &  Reason\\
1707
         \hline 
1708
         No\_Connection       &  There is no connection to disconnect\index{No\_Connection}\\
1709
      \end{tabular}
1710
   \end{center}
1711
   \caption{Disconnect Exceptions}\label{t:dconx}
1712
\end{table}
1713
1714
The following code fragment shows the procedure call in action:
1715
1716
\begin{Example}
1717
declare
1718
   C : Connection_Type;
1719
begin
1720
   ...
1721
   begin
1722
      Disconnect(C);
1723
   exception
1724
      when No_Connection =>
1725
         ...; -- Indicates program logic problem
1726
      when others =>
1727
         raise;
1728
   end;
1729
\end{Example}
1730
1731
\subsection{Procedure Reset}
1732
1733
The Reset\index{Reset} primitive is provided so that the programmer can recycle
1734
the Connection\_Type object for use in a subsequent connection. Without
1735
this primitive, the user would need to destroy the original and create
1736
a new Connection\_Type. The Reset primitive accepts the following
1737
arguments:
1738
1739
\begin{Code}
1740
procedure Reset(
1741
   C : in out Connection_Type
1742
);
1743
\end{Code}
1744
1745
In addition to closing the current connection, if it is open, the
1746
notification procedure is also deregistered (if there was a Set\_Notify\_Proc\index{Set\_Notify\_Proc}
1747
performed).
1748
1749
No exceptions should occur. If there is a connection pending\index{pending connection}, it is
1750
disconnected\index{disconnected}. If there is no connection pending, the call is ignored.
1751
The following shows an example of its use:
1752
1753
\begin{Example}
1754
declare
1755
   C : Connection_Type;
1756
begin
1757
   ...
1758
   Reset(C);  -- C is now ready for re-use
1759
\end{Example}
1760
1761
\section{Connection Information Operations}
1762
1763
A modular\index{modular software} piece of software may get handed a Connection\_Type object
1764
as a parameter, and have a need to inquire about the details of the
1765
provided connection. The function primitives that return information
1766
about the connection are listed in Table~\ref{t:cinfp}.
1767
1768
\begin{table}
1769
   \begin{center}
1770
      \begin{tabular}{ll}
1771
         Function Name     &  Information Returned\\
1772
         \hline 
1773
         Host\_Name        &  Host name of the connection\\
1774
         Port              &  Port Number or Port Pathname\\
1775
         DB\_Name          &  Database name\\
1776
         User              &  User name for the database\\
1777
         Password          &  Password for the database\\
1778
         Instance          &  Instance name for the database\\
1779
         Options           &  Database option parameters\\
1780
      \end{tabular}
1781
   \end{center}
1782
   \caption{Connection Information Primitives}\label{t:cinfp}
1783
\end{table}
1784
1785
These function primitive specifications are listed below:
1786
1787
\begin{Code}
1788
function Host_Name(
1789
   C : Connection_Type;
1790
) return String;
1791
\end{Code}
1792
1793
\begin{Code}
1794
function Port(
1795
   C : Connection_Type;
1796
) return String;  -- UNIX path
1797
\end{Code}
1798
1799
\begin{Code}
1800
function Port(
1801
   C : Connection_Type;
1802
) return Integer; -- TCP/IP port
1803
\end{Code}
1804
1805
\begin{Code}
1806
function DB_Name(
1807
   C : Connection_Type;
1808
) return String;
1809
\end{Code}
1810
1811
\begin{Code}
1812
function User(
1813
   C : Connection_Type;
1814
) return String;
1815
\end{Code}
1816
1817
\begin{Code}
1818
function Password(
1819
   C : Connection_Type;
1820
) return String;
1821
\end{Code}
1822
1823
\begin{Code}
1824
function Instance(
1825
   C : Connection_Type;
1826
) return String;
1827
\end{Code}
1828
1829
\begin{Code}
1830
function Options(
1831
   C : Connection_Type;
1832
) return String;
1833
\end{Code}
1834
1835
The Port\index{Port} primitive that returns a String is for use with database
1836
connections using a UNIX socket\index{UNIX socket}\index{local socket}. The socket
1837
pathname\index{pathname} is returned in this case.
1838
\footnote{or at least a fragment of the pathname.}
1839
1840
When called on Connection\_Type objects without a current connection,
1841
an empty string\index{string, empty} is returned for any value that has not been configured
1842
(for example if Set\-\_Host\-\_Name\index{Set\_Host\_Name} has not been called, Host\-\_Name\index{Host\_Name} will
1843
return ""). If the value has been set, then that value is returned
1844
as expected. Once the Connection\-\_Type object is connected to the
1845
database however, the values will be values fetched from the library\index{library}
1846
libpq\index{libpq} instead.
1847
\footnote{Normally, these values should agree with what was configured.}
1848
1849
The following code sample shows how to extract the host name\index{host name} and database
1850
name for the current connection.
1851
1852
\begin{Example}
1853
procedure My_Code(C : in out Connection_Type) is
1854
   Host_Name :     String := Host_Name(C);
1855
   Database_Name : String := DB_Name(C);
1856
begin
1857
   ...
1858
\end{Example}
1859
1860
\begin{description}
1861
\item [Sybase Note:]The Instance function primitive was added to APQ support Sybase.
1862
   See the support level chart for Set\_Instance\index{Set\_Instance} on page \pageref{Set_Instance Support Chart}
1863
   and other information primitives. Note also that setting and retrieving
1864
   other parameters is possible in some cases, even though the information
1865
   is ignored by Sybase.
1866
\end{description}
1867
1868
\section{General Information Operations}
1869
1870
Due to the modular construction of software, it is sometimes necessary
1871
to query an object for its present state. The primitives listed in Table~\ref{t:gifc}
1872
for the Connection\_Type object are available for querying the state\index{query the state}
1873
of the object. These are discussed in the next subsections.
1874
1875
\begin{table}
1876
   \begin{center}
1877
      \begin{tabular}{lll}
1878
         Type  &  Name              &  Purpose\\
1879
         \hline 
1880
         func  &  Is\_Connected     &  Indicates connected state\\
1881
         func  &  Error\_Message    &  Returns a error message text\\
1882
      \end{tabular}
1883
   \end{center}
1884
   \caption{General Information for Connections}\label{t:gifc}
1885
\end{table}
1886
1887
\subsection{Function Is\_Connected}
1888
1889
The Is\_Connected\index{Is\_Connected} function returns a Boolean result that indicates
1890
the present state of the Connection\_Type object. The arguments are
1891
as follows:
1892
1893
\begin{Code}
1894
function Is_Connected(
1895
   C : Connection_Type
1896
) return Boolean;
1897
\end{Code}
1898
1899
There are no exceptions raised by this primitive.
1900
1901
The following example shows how to test if the object C is currently
1902
supporting a connection. The example disconnects from the server,
1903
if it determines that C is connected.
1904
1905
\begin{Example}
1906
declare
1907
   C : Connection_Type;
1908
begin
1909
   ...
1910
   if Is_Connected(C) then
1911
      Disconnect(C);
1912
      ...
1913
\end{Example}
1914
1915
\subsection{Function Error\_Message}
1916
1917
The Error\_Message\index{Error\_Message} function makes it possible for the application
1918
to report why the connection failed. This information is often crucial
1919
to the user of a failed application. The arguments accepted are as
1920
follows:
1921
1922
\begin{Code}
1923
function Error_Message(
1924
   C : Connection_Type
1925
) return String;
1926
\end{Code}
1927
1928
There are no exceptions raised by this function. If there is no present
1929
connection or no present error to report, the null string is returned.
1930
The following example shows how the connection failure is reported:
1931
1932
\begin{Example}
1933
with Ada.Text_IO;
1934
...
1935
declare
1936
   use Ada.Text_IO;
1937
1938
   C : Connection_Type;
1939
begin
1940
   ...
1941
   begin
1942
      Connect(C);
1943
   exception
1944
      when No_Connection =>
1945
         Put_Line(Standard_Error,"Connection Failed!");
1946
         Put_Line(Standard_Error,Error_Message(C));
1947
         ...
1948
      when Already_Connected =>
1949
         ...;  -- Program logic error here
1950
      when others =>
1951
         raise;
1952
   end;
1953
\end{Example}
1954
1955
\subsection{Function Notice\_Message\label{Function Notice_Message}}
1956
1957
The C libpq\index{libpq} interface library\index{library}\footnote{The Notice\_Message function is
1958
not available for MySQL.} provides the APQ binding with certain
1959
notification messages\index{notification messages} during some calls, by means of a callback\index{callback}. Each
1960
time one of these notifications is received from the database server,
1961
the notification message is saved in the Connection\_Type object
1962
(replacing any former notice message). The last notification message
1963
received can be retreived using the Notice\_Message\index{Notice\_Message} function:
1964
1965
\begin{Code}
1966
function Notice_Message(
1967
   C : Connection_Type
1968
) return String;
1969
\end{Code}
1970
1971
No exception is raised, and the null string\index{null string} is returned if no notice
1972
message has been registered.
1973
1974
The following example illustrates one example of the Notice\_Message
1975
function:
1976
1977
\begin{Example}
1978
with Ada.Text_IO;
1979
...
1980
declare
1981
   use Ada.Text_IO;
1982
1983
   C : Connection_Type;
1984
begin
1985
   ...
1986
   declare
1987
      Msg : String := Notice_Message(C);
1988
   begin
1989
      if Msg'Length > 0 then
1990
         Put_Line(Standard_Error,Msg);
1991
         ...
1992
\end{Example}
1993
1994
\subsection{In\_Abort\_State Function\label{In_Abort_State Function}}
1995
1996
\Ref{Abort_State exception} documents the Abort\_State\index{Abort\_State}
1997
exception, which is unique to PostgreSQL\index{PostgreSQL}. This exception is raised in
1998
response to a status flag stored in the
1999
APQ\-.PostgreSQL\-.Client\-.Connection\_Type object. When a transaction is
2000
started, any SQL error\index{SQL error} will put the PostgreSQL database server into an
2001
``\emph{abort state}'', where all current and future commands will be
2002
ignored, for the connection \footnote{MySQL does not support this
2003
concept, and so it does not go into an abort state.}. To permit the
2004
application programmer to query this status, the In\_Abort\_State\index{In\_Abort\_State}
2005
function can be used. It returns True, if an error has occurred within a
2006
transaction, which requires a Rollback\_Work (\Ref{Begin, Commit and Rollback Work functions})
2007
call to clear this state. The calling
2008
requirements are summarized in the following table:
2009
2010
\begin{Code}
2011
function In_Abort_State(
2012
   C : Connection_Type
2013
) return Boolean;
2014
\end{Code}
2015
2016
Exceptions for In\_Abort\_State are summarized in Table~\ref{t:iasx}.
2017
2018
\begin{table}
2019
   \begin{center}
2020
      \begin{tabular}{ll}
2021
         Exception Name    &  Reason\\
2022
         \hline 
2023
         Not\_Connected    &  There is no connection to query\\
2024
      \end{tabular}
2025
   \end{center}
2026
   \caption{In\_Abort\_State Exceptions}\label{t:iasx}
2027
\end{table}
2028
2029
The following example shows how this function might be used:
2030
2031
\begin{Example}
2032
declare
2033
   C : Connection_Type;
2034
   Q : Query_Type;
2035
begin
2036
   ...
2037
   Begin_Work(Q,C);
2038
   ...
2039
   Execute(Q,C);
2040
   ...
2041
   if In_Abort_State(C) then
2042
      Rollback(Q,C);
2043
      ...
2044
   end if;
2045
\end{Example}
2046
2047
\section{Implicit Operations}
2048
2049
There are a few implicit operations\index{implicit operations} that are performed that the programmer
2050
should be aware of. They are:
2051
2052
\begin{itemize}
2053
   \item The Connection\_Type is subject to Finalization
2054
   \item A default Commit/Rollback operation can occur at Finalization
2055
\end{itemize}
2056
2057
The programmer is encouraged to call Commit\_Work\index{Commit\_Work} or Rollback\_Work\index{Rollback\_Work}
2058
explicitly, whenever possible. This way, the programmer is in complete
2059
control of the transaction outcome.
2060
2061
If a transaction has not been committed or rolled back, and the connected
2062
Connection\_Type object is finalized\index{finalization}%
2063
\footnote{Usually because the Connection\_Type object has fallen out of scope.%
2064
}, then the default action for commit or rollback occurs. The default
2065
for the APQ binding is to rollback the transaction, when the connection
2066
is still active. If the programmer has disconnected\index{disconnected} from the database
2067
prior to finalization, then no further action occurs. To change or
2068
control the default action, use the Set\_Rollback\_On\_Finalize\index{Set\_Rollback\_On\_Finalize} procedure
2069
described in the next section.
2070
2071
2072
\subsection{Set\_Rollback\_On\_Finalize Procedure\label{Set_Rollback_On_Finalize Procedure}}
2073
2074
The Set\_Rollback\_On\_Finalize primitive allows the programmer to
2075
change the default action for the Connection\_Type object. The calling
2076
requirements are summarized in the following table:%
2077
2078
\begin{Code}
2079
procedure Set_Rollback_On_Finalize(
2080
   C :        in out Connection_Type;
2081
   Rollback : in     Boolean
2082
);
2083
\end{Code}
2084
2085
To change the default to COMMIT WORK\index{COMMIT WORK} when the Connection\_Type object
2086
finalizes, peform the following call:
2087
2088
\begin{Example}
2089
declare
2090
   C : Connection_Type;
2091
begin
2092
   Set_Rollback_On_Finalize(C,False); -- Commit on Finalize
2093
\end{Example}
2094
2095
\subsection{Will\_Rollback\_On\_Finalize Function\label{Will_Rollback_On_Finalize Function}}
2096
2097
Programs sometimes need to inquire about the state of the Connection\_Type
2098
object that they may have been passed. To inquire about the commit
2099
or rollback default, the Will\_Rollback\_On\_Finalize\index{Will\_Rollback\_On\_Finalize} function can
2100
be called. The following table summarizes the calling requirements:
2101
2102
\begin{Code}
2103
function Will_Rollback_On_Finalize(
2104
   C : Connection_Type
2105
) return Boolean;
2106
\end{Code}
2107
2108
\section{Trace Facilities\label{Trace Facilities}}
2109
2110
No matter how carefully a programmer writes a new program, problems
2111
develop that are often difficult to understand. Good tracing facilities\index{trace facilities}
2112
allow the problem to be quickly understood and corrected.
2113
2114
To gain trace support using APQ, it is only necessary to perform the
2115
following steps:
2116
2117
\begin{enumerate}
2118
   \item Open a trace capture file with Open\_DB\_Trace
2119
   \item Optionally enable/disable tracing at various points in the program
2120
      with Set\_Trace%
2121
      \footnote{Tracing is enabled by default after a Open\_DB\_Trace call.}
2122
   \item Perform your SQL operations
2123
   \item Close the trace capture file with Close\_DB\_Trace%
2124
      \footnote{Or allow it to be closed when the Connection\_Type object is finalized.}
2125
\end{enumerate}
2126
2127
The Open\_DB\_Trace\index{Open\_DB\_Trace} procedure takes a Trace\_Mode\_Type\index{Trace\_Mode\_Type} parameter
2128
that decides what trace content is being collected. The valid enumerated
2129
choices are listed in Table~\ref{t:tmchoic}.
2130
2131
\begin{table}
2132
   \begin{center}
2133
      \begin{tabular}{ll}
2134
         Value           & Description\\
2135
         \hline
2136
         APQ.Trace\_None & Collect no trace information (no file is written/created)\\
2137
         APQ.Trace\_DB   & Collect only C library trace information%
2138
            \footnote{Prior to APQ 2.0, this was Trace\_libpq.}\\
2139
         APQ.Trace\_APQ  & Collect only APQ SQL trace information\\
2140
         APQ.Trace\_Full & Collect both database library and Trace\_APQ information\\
2141
      \end{tabular}
2142
   \end{center}
2143
   \caption{Trace\_Mode\_Type Choices}\label{t:tmchoic}
2144
\end{table}
2145
2146
The Trace\_None\index{Trace\_None} value is provided so that the Open\_DB\_Trace procedure
2147
does not need to be coded around if a trace variable is supplied,
2148
which may or may not request tracing. Close\_DB\_Trace\index{Close\_DB\_Trace} can be called
2149
on a Connection\_Type\index{Connection\_Type} for which Trace\_None is in effect, without
2150
any exception being thrown (the call is ignored).
2151
2152
Trace\_DB\index{Trace\_DB} provides only what the C library (libpq\index{libpq} for PostgreSQL\index{PostgreSQL})
2153
provides. This may be useful to the database software maintainers,
2154
if they want a trace of the activity that you are reporting problems
2155
with.
2156
2157
Trace\_APQ\index{Trace\_APQ} is what the author considers to be the most useful output
2158
format to an APQ developer. The trace output in this mode is such
2159
that the extra trace information is provided in SQL comment\index{SQL comment} form.
2160
The actual queries that are executed are in their natural SQL form.
2161
The captured Trace\_APQ trace then, is in a format that can be played
2162
back, reproducing exactly what the application performed.%
2163
\footnote{There are limitations however, since the blob functions are not traced
2164
at the present release.%
2165
} The full trace or portions of it then can be used to help debug SQL
2166
related problems. 
2167
2168
The following shows a sample of what the Trace\_APQ output looks like:
2169
2170
\begin{SQL}
2171
-- Start of Trace, Mode=TRACE_APQ
2172
-- SQL QUERY:
2173
BEGIN~WORK}
2174
;
2175
-- Result: 'BEGIN'
2176
2177
-- SQL QUERY:
2178
INSERT INTO DOCUMENT
2179
       (NAME,DOCDATE,BLOBID,CREATED,MODIFIED,ACCESSED)
2180
VALUES ('compile.adb','2002-08-12~21:09:25',3339004,
2181
        '2002-08-12~21:59:48','2002-08-12~21:09:25',
2182
        '2002-08-19~22:11:36')
2183
;
2184
-- Result: 'INSERT 3339005 1'
2185
2186
-- SQL QUERY:
2187
SELECT DOCID
2188
FROM DOCUMENT
2189
WHERE OID = 3339005
2190
;
2191
-- Result: 'SELECT'
2192
...
2193
-- SQL QUERY:
2194
COMMIT WORK
2195
;
2196
-- Result: 'COMMIT'
2197
-- End of Trace.
2198
\end{SQL}
2199
2200
The following subsections describe the primitives that provide support
2201
for trace facilities.
2202
2203
2204
\subsection{Procedure Open\_DB\_Trace}
2205
2206
To start any capture of trace\index{trace capture} information, you must specify the name
2207
of the text file to be written to. The file must be writable to the
2208
current process. The Connection\_Type object must be connected prior
2209
to calling Open\_DB\_Trace\index{Open\_DB\_Trace}:
2210
2211
\begin{Code}
2212
procedure Open_DB_Trace(
2213
   C :        in out Connection_Type;
2214
   Filename : in     String;
2215
   Mode :     in     Trace_Mode_Type := Trace_APQ
2216
);
2217
\end{Code}
2218
2219
Table \ref{t:odbtx} lists the possible exceptions for Open\_DB\_Trace.
2220
2221
\begin{table}
2222
   \begin{center}
2223
      \begin{tabular}{ll}
2224
         Exception Name & Reason\\
2225
         \hline 
2226
         Not\_Connected & There is no connection\\
2227
         Tracing\_State & Trace is already enabled\\
2228
      \end{tabular}
2229
   \end{center}
2230
   \caption{Open\_DB\_Trace Exceptions}\label{t:odbtx}
2231
\end{table}
2232
2233
Upon return from the Open\_DB\_Trace procedure, a text file will be
2234
created and ready to have trace entries written to it.%
2235
\footnote{Note that trace entries are buffered by C standard I/O routines, so
2236
trace information may be held in memory buffers before it is flushed
2237
out or closed.%
2238
}
2239
2240
The following example shows how a call might be coded:
2241
2242
\begin{Example}
2243
declare
2244
   C : Connection_Type;
2245
begin
2246
   ...
2247
   Open_DB_Trace(C,"./bugs.sql",Trace_APQ);
2248
\end{Example}
2249
2250
\subsection{Procedure Close\_DB\_Trace}
2251
2252
Closing the tracing facility for a connection, suspends all further
2253
trace writes. Once this has been done, the effect of Set\_Trace\index{Set\_Trace} is
2254
superceeded, preventing any further trace information being written.
2255
The calling requirements are outlined in the following table:
2256
2257
\begin{Code}
2258
procedure Close_DB_Trace(
2259
   C : in out Connection_Type
2260
);
2261
\end{Code}
2262
2263
If the Open\_DB\_Trace call was made with the Mode parameter set to
2264
Trace\_None, then the call to Close\_DB\_Trace\index{Close\_DB\_Trace} has no effect and is
2265
ignored for programmer convenience.
2266
2267
No exceptions are raised.
2268
2269
An example call is shown below:
2270
2271
\begin{Example}
2272
declare
2273
   C : Connection_Type;
2274
begin
2275
   ...
2276
   Open_DB_Trace(C,"./bugs.sql",Trace_APQ);
2277
   ...
2278
   Close_DB_Trace(C);
2279
\end{Example}
2280
2281
\subsection{Procedure Set\_Trace}
2282
2283
In large applications where large numbers of SQL statements are executed,
2284
it may be desirable to trace only certain parts of its execution in
2285
a dynamic fashion. The Set\_Trace\index{Set\_Trace} primitive gives the programmer a
2286
way to disable and re-enable tracing at strategic\index{strategic tracing} points within the
2287
application. The calling requirements are summarized as follows:
2288
2289
\begin{Code}
2290
procedure Set_Trace(
2291
   C :        in out Connection_Type;
2292
   Trace_On : in     Boolean := True
2293
);
2294
\end{Code}
2295
2296
Tracing is enabled by default, after a successful call to Open\_DB\_Trace
2297
is made (unless Mode was Trace\_None\index{Trace\_None}).
2298
2299
There are no exceptions raised.
2300
2301
Note that it is considered safe to invoke Set\_Trace, even if a former
2302
Open\_DB\_Trace call was not successfully performed, or the trace
2303
mode was Trace\_None. This allows the application to retain strategic
2304
Set\_Trace calls without having to remove them, when the Open\_DB\_Trace
2305
call is disabled%
2306
\footnote{Setting Mode to Trace\_None effectively disables the trace facility
2307
without requiring any code changes.%
2308
} or commented out.
2309
2310
2311
\subsection{Function Is\_Trace}
2312
2313
It may be helpful to the developer that is tracking down a problem
2314
to know when tracing is enabled or not. The Is\_Trace\index{Is\_Trace} function returns
2315
true when the trace collection file is receiving trace information.
2316
The calling arguments are listed below:%
2317
2318
Note that the returned value tracks the last value provided by
2319
Set\_Trace, whether or not an open trace file has been created/opened.
2320
2321
\begin{Code}
2322
function Is_Trace(
2323
   C : Connection_Type;
2324
) return Boolean;
2325
\end{Code}
2326
2327
Note that the initial state of the Connection\_Type object is to have
2328
Is\_Trace to return True. Also after a successful Open\_DB\_Trace,
2329
Is\_Trace will return True.
2330
2331
An example showing its use is given below:
2332
2333
\begin{Example}
2334
declare
2335
   C : Connection_Type;
2336
begin
2337
   ...
2338
   Open_DB_Trace(C,"./bugs.sql",Trace_APQ);
2339
   ...
2340
   if Is_Trace(C) then
2341
      -- We are collecting trace info..
2342
\end{Example}
2343
2344
\section{Generic Database Operations}
2345
2346
APQ 2.0 and later is designed so that all but the most specialized
2347
database operations, can be performed, given only a Root\_Connection\_Type'Class\index{Root\_Connection\_Type'Class}
2348
object (declared in top level package APQ). The following sections
2349
describe some generic database related primitives that are necessary
2350
for successful generic database support.
2351
2352
2353
\subsection{Package APQ}
2354
2355
Root object support\index{root object support} is provided in the package APQ\index{APQ, package}. Generic database
2356
code will normally only use this package:
2357
2358
\begin{Code}
2359
   with APQ;
2360
2361
   use APQ;  -- Optional use clause
2362
\end{Code}
2363
2364
The data types that will be used will be:
2365
2366
\begin{itemize}
2367
   \item APQ.Root\_Connection\_Type'Class
2368
   \item APQ.Root\_Query\_Type'Class\index{Root\_Query\_Type'Class}
2369
\end{itemize}
2370
2371
The generic primitives that will be covered in the next section are:
2372
2373
\begin{itemize}
2374
   \item APQ.Engine\_Of
2375
   \item APQ.New\_Query
2376
\end{itemize}
2377
2378
\subsection{Predicate Engine\_Of\label{Generic Database Engine_Of}}
2379
2380
Given a Root\_Connection\_Type'Class object, generic database code
2381
sometimes needs to determine which specific database is being used.
2382
This allows the code to make special SQL syntax changes, depending
2383
upon the technology being used (for example, MySQL\index{MySQL} permits the use
2384
of a \emph{LIMIT}\index{LIMIT} keyword in queries).
2385
2386
The Engine\_Of\index{Engine\_Of} primitive (dispatching) will identify the
2387
database technology that is being used:
2388
2389
\begin{Code}
2390
type Database_Type is (
2391
   Engine_PostgreSQL,
2392
   Engine_MySQL,
2393
   Engine_Sybase
2394
);
2395
2396
function Engine_Of(
2397
   C : Connection_Type
2398
) return Database_Type;
2399
\end{Code}
2400
2401
The following example code shows how to test if a PostgreSQL\index{PostgreSQL} database
2402
is being used:
2403
2404
\begin{Example}
2405
with APQ; use APQ;
2406
...
2407
procedure App(C : Root_Connection_Type'Class) is
2408
begin
2409
   ...
2410
   if Engine_Of(C) = Engine_PostgreSQL then
2411
      ...
2412
\end{Example}
2413
2414
\subsection{Primitive New\_Query\label{Query_Type Factories}}
2415
2416
Normally, an application database procedure will receive a connection
2417
object as one of its input parameters. Generally, this connection
2418
is established in the main program and then used by the program components
2419
as required. However, to pass the parameter in a generic way (allowing
2420
for polymorphism), you would declare the procedure's argument as receiving
2421
data type Root\_Connection\_Type'Class.
2422
2423
Within the called procedure however, you will need a Query\_Type object.
2424
This too could be passed in as an argument, but this is unnecessary.
2425
At other times, you may need additional Query\_Type objects for temporary
2426
use. What you need is a convenient way to create a Query\_Type object
2427
that matches the connection that you have received as a parameter. This
2428
is done by the New\_Query function\index{New\_Query}.
2429
2430
If your connection object is a:
2431
2432
\begin{Code}
2433
2434
   APQ.PostgreSQL.Client.Connection_Type
2435
2436
\end{Code}
2437
2438
object, then your application will want to create a:
2439
2440
\begin{Code}
2441
2442
   APQ.PostgreSQL.Client.Query_Type
2443
2444
\end{Code}
2445
2446
object. You want to avoid tests like:
2447
2448
\begin{Example}
2449
2450
if Connection is in APQ.PostgreSQL.Client.Connection_Type then
2451
   ...
2452
elsif Connection is in APQ.MySQL.Client.Connection_Type then
2453
   ...
2454
elsif Connection is in APQ.Sybase.Client.Connection_Type then
2455
   ...
2456
2457
\end{Example}
2458
2459
The above example code would force your portable code to also ``with''\index{with}
2460
the following packages:
2461
2462
\begin{Example}
2463
with APQ.PostgreSQL.Client;
2464
with APQ.MySQL.Client;
2465
...
2466
\end{Example}
2467
2468
which would be very inconvenient and unnecessary.
2469
2470
To make portable\index{portable} database programming easier, APQ provides a dispatching\index{dispatching}
2471
Query\_Type object factory primitive that can be used for this purpose.
2472
For example:
2473
2474
\begin{NumberedExample}
2475
with APQ;
2476
use APQ;
2477
2478
procedure My_Generic_App(C : Root_Connection_Type'Class) is
2479
   Q : Root_Query_Type'Class := New_Query(C);\label{Ex:New_Query_Assgn}
2480
begin
2481
   Prepare(Q,"SELECT NAME,INCOME");
2482
   Append_Line(Q,"FROM~SALARIES");
2483
\end{NumberedExample}
2484
2485
The assignment to Q in line~\ref{Ex:New_Query_Assgn}, shows the
2486
application of the primitive New\_Query. This dispatching
2487
primitive returns the correct Query\_Type object that matches the
2488
connection that was given. The primitive New\_Query is more formally
2489
presented as follows:
2490
2491
\begin{Code}
2492
function New_Query(
2493
   C : Root_Connection_Type
2494
) return Root_Query_Type'Class;
2495
\end{Code}
2496
2497
\subsection{Query\_Type Assignment\label{Query_Type Cloning}}
2498
2499
Prior to APQ version 2.0, the Query\_Type object was a \emph{limited}\index{limited tagged type}
2500
tagged type. This meant that the Query\_Type object was never able
2501
to be assigned to another Query\_Type object. With the need for a
2502
factory\index{factory} primitive like \textbf{New\_Query} it was necessary to lift
2503
that restriction (otherwise the factory was unable to return the created
2504
object). So the Root\_Query\_Type and derived forms, permit assignment
2505
as of APQ version 2.0 and later.
2506
2507
When a Query\_Type is assigned in APQ, nothing spectacular happens.
2508
In fact, the contents of the object on the right hand side are effectively
2509
ignored, leaving a new object on the left side. The following example
2510
shows how Q1 and Q2 are essentially the same:
2511
2512
\begin{NumberedExample}
2513
declare
2514
   Q0 : Query_Type;
2515
   Q1 : Query_Type;
2516
   Q2 : Query_Type;
2517
begin
2518
   ...
2519
   Q1 := Q0;   -- Q1 becomes initialized (Q0 ignored)\label{Ex:Q1}
2520
   Clear(Q2);  -- Initialize Q2\label{Ex:Q2}
2521
\end{NumberedExample}
2522
2523
In this example, both Q1~(line~\ref{Ex:Q1}) and Q2~(line~\ref{Ex:Q2})
2524
end up in the same state, and no state information is taken from Q0. You
2525
might wonder why this would be implemented. The following example code
2526
fragment illustrates why this is convenient and useful:
2527
2528
\begin{NumberedExample}
2529
with APQ;
2530
usse APQ;
2531
2532
procedure My_Generic_App(C : Root_Connection_Type'Class) is
2533
   Q : Root_Query_Type'Class := New_Query(C);
2534
begin
2535
   Prepare(Q,"SELECT NAME, INCOME");
2536
   Append(Q, "FROM~SALARIES");
2537
   Execute(Q,C);
2538
   ...
2539
   declare
2540
      Q2 : Root_Query_Type'Class := Q;\label{Ex:Q_Clone}
2541
   begin
2542
      ...
2543
   end;
2544
\end{NumberedExample}
2545
2546
The example illustrates that the assignment (line~\ref{Ex:Q_Clone}) is
2547
simply a convenient factory of its own kind. It is also likely to be
2548
slightly more efficient than the New\_Query primitive on the
2549
connection. Think of assignment of Query\_Type objects as cloning\index{cloning}
2550
operations. The assigned object becomes a fresh initialized clone of the
2551
Query\_Type object on the right hand side of the assignment.
2552
2553
\chapter{SQL Query Support}
2554
2555
Once a database connection has been established, the application is
2556
ready to invoke operations on the database server. To ease the programmer's
2557
burden in keeping track of the various components involved in these
2558
transactions, the Query\_Type object is provided. The Query\_Type\index{Query\_Type}
2559
object and the Connection\_Type object are used together when it comes
2560
time to execute the query. Some operations require the connection
2561
object, while others do not.
2562
2563
There are a large number of primitives associated with the Query\_Type
2564
object. Most of them are related to the large number of data types
2565
that are supported. These Query\_Type primitives fall into the following
2566
basic categories:
2567
2568
\begin{enumerate}
2569
   \item Object initialization
2570
   \item SQL Query building
2571
   \item SQL Execution on the Database server
2572
   \item Transaction operations
2573
   \item Fetch operations
2574
   \item Column information functions
2575
   \item Value fetching functions
2576
   \item Value and Indicator fetching procedures
2577
   \item Information operations
2578
\end{enumerate}
2579
2580
In addition to these, are a number of generic functions and procedures
2581
that permit the APQ user to custom tailor the API to his own specialized
2582
Ada data types. This allows applications to continue the follow the
2583
healthy tradition of using strong data types. There is no need for
2584
a database application to take a back seat to safety\index{safety}.
2585
2586
\section{Initialization \label{SQL Initialization}}
2587
2588
The Query\_Type object is initialized when the object is created.
2589
However, the Query\-\_Type object can be re-used as various SQL\index{SQL}
2590
operations are performed by the program. To re-use the Query\_Type
2591
object, one of the primitives in Table~\ref{t:qinit} may be used to recycle it for
2592
re-use.
2593
2594
\begin{table}
2595
   \begin{center}
2596
      \begin{tabular}{lll}
2597
         Type  &  Name     &  Purpose\\
2598
         \hline
2599
         proc  &  Clear    &  Clear object and re-initialize\\
2600
         proc  &  Prepare  &  Reinitialize with start of new SQL query\\
2601
      \end{tabular}
2602
   \end{center}
2603
   \caption{Query Initialization}\label{t:qinit}
2604
\end{table}
2605
2606
The Clear\index{Clear} procedure does the initialization of the Query\_Type object.
2607
The Prepare primitive implicitly invokes Clear
2608
\footnote{Consequently, your application need not invoke Clear() prior to calling
2609
Prepare().} and additionally starts the building of an SQL query. Very short
2610
SQL statements may comletely specified by the Prepare API call. Longer
2611
queries can be completed with some of the other primitives to be discussed
2612
in this section.
2613
2614
\subsection{Procedure Clear}
2615
2616
With one exception, the Clear\index{Clear} primitive completely resets the state
2617
of the Query\_Type object. This function primitive serves to basic
2618
purposes:
2619
2620
\begin{enumerate}
2621
\item Resets the object to its initial state so that it can be reused for a new query.
2622
\item Releases any results of the current query (close cursors etc.)
2623
\end{enumerate}
2624
2625
When performed after a query has been executed, this primitive releases
2626
all results from the query. For Sybase, this can include issuing a
2627
cancel back to the server and flushing all pending row results that
2628
have not been retrieved by the APQ client program.
2629
2630
Clear accepts the Query\_Type object as its only argument:
2631
2632
\begin{Code}
2633
procedure Clear(
2634
   Q : in out Query_Type
2635
);
2636
\end{Code}
2637
2638
The one exception to clearing state however, is that the SQL case\index{case policy}
2639
policy remains unchanged. If prior to the clear, the SQL case policy
2640
is set to Preserve\_Case\index{Preserve\_Case}, it will remain so after the Clear call.
2641
2642
There are no exceptions raised by this call.
2643
2644
The use of the Clear primitive is recommended after all SQL processing
2645
related to the query has been completed. This permits any database
2646
server results to be released. Think of it as ``closing''\index{closing a query} the
2647
query. Note however, that object finalization\index{finalization} will take care of this,
2648
if the job is left unfinished by the programmer.
2649
2650
The following example illustrates it's use:
2651
2652
\begin{Example}
2653
declare
2654
   C : Connection_Type;
2655
   Q : Query_Type;
2656
begin
2657
   ...
2658
   Clear(Q);
2659
\end{Example}
2660
2661
\subsubsection{Performance Issue}
2662
2663
There is one particular case where calling Clear is vitally important
2664
for some database products. Let's use an example where you are fetching
2665
the most recent stock price from a price history file. Here is the
2666
table declaration:
2667
2668
\begin{SQL}
2669
CREATE TABLE PRICE_HIST (
2670
   SECURITY    CHAR(10) NOT NULL,
2671
   PRICE_DATE  DATE NOT NULL,
2672
   PRICE       REAL,
2673
   PRIMARY KEY (SECURITY,PRICE_DATE)
2674
);
2675
\end{SQL}
2676
2677
With this table holding price history, keyed by the security name
2678
and date, we can lookup the most recent price with a subroutine something
2679
like the following:
2680
2681
\begin{NumberedExample}
2682
procedure Last_Price(
2683
   C :        in out Root_Connection_Type'Class;
2684
   Security : in     String;
2685
   Price :       out APQ_Double
2686
) is
2687
   function Value is new Float_Value(APQ_Double);
2688
2689
   Q : Root_Query_Type'Class := New_Query(C);\label{Ex:TheQ}
2690
begin
2691
2692
   Begin_Work(Q,C);
2693
2694
   Prepare(Q,    "SELECT SECURITY,PRICE_DATE,PRICE");
2695
   Append_Line(Q,"FROM PRICE_HIST");
2696
   Append(Q,     "WHERE SECURITY = ");
2697
   Append_Quoted(Q,C,Security,Line_Feed);
2698
   Append_Line(Q,"ORDER BY SECURITY,PRICE_DATE DESC");\label{Ex:OrderBy}
2699
2700
   if Engine_Of(C) = Engine_MySQL then
2701
      Append_Line(Q,"LIMIT 1");\label{Ex:Limit1}
2702
   end if;
2703
2704
   Execute(Q,C);
2705
2706
   begin
2707
      Fetch(Q);
2708
   exception
2709
      when No_Tuple =>
2710
         raise;   -- No price found!
2711
   end;
2712
2713
   Price := Value(Q,3);
2714
   Clear(Q);\label{Ex:Clear}
2715
2716
end Last_Price;
2717
\end{NumberedExample}
2718
2719
In this example, you can see that MySQL\index{MySQL} is covered by adding the "LIMIT 1"\index{LIMIT}
2720
clause in line~\ref{Ex:Limit1}.\footnote{MySQL will limit the results to 1 row, if any.}
2721
PostgreSQL\index{PostgreSQL} does not have a problem with this type of query because each row is
2722
fetched on demand. Sybase\index{Sybase} however, will start returning all the rows
2723
that it has available, in the order specified by the "ORDER BY"\index{ORDER BY} clause
2724
(line~\ref{Ex:OrderBy}).
2725
2726
Given that the routine Last\_Price only calls Fetch\index{Fetch}
2727
once, there is no point in the Sybase server producing and sending
2728
more row data down the connection to the APQ client program. For this
2729
reason, a call to Clear\index{Clear} (line~\ref{Ex:Clear}) will send a cancel notice to the Sybase server
2730
to stop producing additional rows. It will also clear out any row data on
2731
the connection that has not been fetched by the client program.
2732
2733
In this particular example, the Query\_Type object Q (line~\ref{Ex:TheQ}) would have been
2734
finalized\index{finalized} anyway upon return from Last\_Price. Finalized Query\_Type
2735
objects always perform the equivalent of a call to Clear prior to
2736
releasing the object storage. However, it is important to explicitly
2737
call Clear\index{Clear} if you have many other operations that follow the query
2738
performed in order to allow a timely cancel if necessary and to release
2739
any pending query results.
2740
2741
2742
\subsection{Procedure Prepare\label{Procedure Prepare}}
2743
2744
The Prepare\index{Prepare} primitive goes one step further than Clear
2745
in that it readies the object for the start of an SQL\index{SQL} statement build.
2746
If the query is short, this will be the only building step required.
2747
As in the case of Clear, the SQL case policy\index{case policy} is unchanged however.
2748
2749
The Prepare procedure takes the following arguments:
2750
2751
\begin{Code}
2752
procedure Prepare(
2753
   Q :     in out Query_Type;
2754
   SQL :   in     String;
2755
   After : in     String := Line_Feed
2756
);
2757
\end{Code}
2758
2759
The SQL argument defines the start of your SQL\index{SQL} statement. The
2760
After argument may supply either the default (line feed)\index{line feed} or
2761
some other text to append to the SQL text\index{SQL text}.
2762
It is provided as a programmer convenience, since many times the
2763
programmer will need to append a comma for example.
2764
2765
There are no exceptions raised by this call.
2766
2767
The following code shows an example of building a query to drop a
2768
table:
2769
2770
\begin{Example}
2771
declare
2772
   Q : Query_Type;
2773
begin
2774
   ...
2775
   Prepare(Q,"DROP TABLE DEAD_WEIGHT");
2776
\end{Example}
2777
2778
\section{SQL Query Building \label{SQL Query Building}}
2779
2780
The previous section primitives ``cleared'' the Query\_Type for
2781
a new query. The primitives provided in this section help to build
2782
a new SQL query or to continue (append to)\index{append} the one started by the
2783
Prepare call in \Ref{Procedure Prepare}. The programmer may
2784
start\index{start} with a Prepare call and follow it by a number of ``append''
2785
calls, or call Clear and build upon an empty query\index{empty query} and skip the
2786
Prepare. ``PREPARE''\index{PREPARE} however, is a traditional first step
2787
in embedded SQL\index{embedded SQL} software, so this tradition comes recommended
2788
by the author.
2789
2790
There are two broad categories of support for creating SQL queries\index{SQL queries}.
2791
They are:
2792
2793
\begin{enumerate}
2794
   \item Append\index{Append} a value to the SQL query
2795
   \item Encode\index{Encode} a value or NULL\index{NULL}, to the SQL query.
2796
\end{enumerate}
2797
2798
Both of these categories append to the current query. Primitives in
2799
category 2 , are prefixed with Encode and will be described
2800
later in the present chapter. 
2801
2802
The Append category of support is useful for values that are never
2803
\emph{NULL} (in SQL terms these columns that are declared as ``NOT
2804
NULL''\index{NOT NULL}). The Encode category of support is provided for values in
2805
your application that may be in the NULL\index{NULL} state. It is not absolutely
2806
required that the Encode support be used, since it is possible for
2807
the application to test for a NULL value. However, the programmer
2808
will find that the Encode support provides application coding convenience
2809
and economy of expression. With compact code, better readability\index{readability} and
2810
safety\index{safety} is normally obtained.
2811
2812
Within category 1, there are five groups of primitives%
2813
\footnote{The generic procedures have been lumped in with the primitives.%
2814
} that build on the present query. They are:
2815
2816
\begin{enumerate}
2817
   \item Append a string
2818
   \item Append a string and a \emph{{}``newline''}
2819
   \item Append a quoted string%
2820
      \footnote{Quoted values are always spared from any automatic case conversions,
2821
      if any are applied.}
2822
   \item Append non string types
2823
   \item Append using generic procedures for custom types
2824
\end{enumerate}
2825
2826
Encode\index{Encode} support on the other hand, only provides for the needs of variables
2827
that must be communicated to the database server. As a result, the
2828
encode procedures consist only of the following two groups:
2829
2830
\begin{enumerate}
2831
   \item Encode non-string\index{non-string types} types
2832
   \item Encode using generic procedures for custom types\index{custom types}
2833
\end{enumerate}
2834
2835
Presently only the second group is provided for by the APQ binding.%
2836
\footnote{The reasoning is that most of the time, the user will want to instantiate
2837
the generic procedures anyway. This permits both the data type and
2838
the null indicator\index{null indicator} type to be a custom application type.%
2839
} A future release may expand on category 1 support.
2840
2841
The append procedures (category 1) will be described first and then
2842
followed by the encode procedures (category 2).
2843
2844
2845
\subsection{Append SQL String}
2846
2847
The Append\index{Append} procedure permits the programmer to append text to the
2848
SQL query being saved in the Query\_Type object. Unlike Prepare\index{Prepare},
2849
Append does not clear the object. Append continues to add
2850
SQL text\index{SQL text} to the query already gathered by the object Q (below):
2851
2852
\begin{Code}
2853
procedure Append(
2854
   Q :     in out Query_Type;
2855
   SQL :   in     String;
2856
   After : in     String := ""
2857
);
2858
\end{Code}
2859
2860
\begin{Code}
2861
procedure Append(
2862
   Q :     in out Query_Type;
2863
   SQL :   in     Ada.Strings.Unbounded.Unbounded_String;
2864
   After : in     String := ""
2865
);
2866
\end{Code}
2867
2868
There are no exceptions raised by this call.
2869
2870
The following example shows how Append is used:
2871
2872
\begin{Example}
2873
declare
2874
   Q : Query_Type;
2875
begin
2876
   ...
2877
   Prepare(Q,"SELECT CUSTNO,CUST_NAME");
2878
   Append(Q, "FROM CUSTOMER");
2879
\end{Example}
2880
2881
Note that the Prepare\index{Prepare} call uses a default argument After=New\_Line\index{After}\index{New\_Line},
2882
while Append uses a null string\index{null string} default.
2883
You can put a line break in the SQL query by supplying the
2884
value New\_Line in the argument "After" if you like.
2885
The following example illustrates the use of Prepare and Append:
2886
2887
\begin{Example}
2888
declare
2889
   Q : Query_Type;
2890
   Col_Name_1 : constant String := "CUSTNO";
2891
   Col_Name_2 : constant String := "CUST_NAME";
2892
begin
2893
   ...
2894
   Prepare(Q,"SELECT ");
2895
   Append(Q,Col_Name_1,",");
2896
   Append(Q,Col_Name_2,Line_Feed);
2897
   Append(Q,"FROM CUSTOMER");
2898
\end{Example}
2899
2900
This example builds up the same query that the previous example did,
2901
except that the column names were provided by string variables\index{string variables}.
2902
2903
\subsection{Append SQL Line\label{Append SQL Line}}
2904
2905
The Append\_Line\index{Append\_Line} procedure is provided for added convenience and program
2906
readability\index{readability}. The same effect can be had with a string Append call,
2907
using string APQ.Line\_Feed supplied as the After\index{After} argument.
2908
The Append\_Line procedure has the following specification:
2909
2910
\begin{Code}
2911
procedure Append_Line(
2912
   Q :   in out Query_Type;
2913
   SQL : in     String;
2914
);
2915
\end{Code}
2916
2917
The Append\_Line procedure is one of the few that does not sport an
2918
\emph{After} argument.
2919
2920
2921
\subsection{Append Quoted SQL String}
2922
2923
Don't quote\index{quoted strings} your own strings at home. There are several reasons why
2924
supplying your own quotes to a call to the normal Append call is a
2925
bad idea:
2926
2927
\begin{enumerate}
2928
   \item Some characters must be encoded\index{encoded} or escaped\index{escaped}, if they occur in the string.
2929
   \item SQL portability\index{portability} is enhanced, since encoding and escaping\index{escaping} varies from
2930
      database vendor to vendor.
2931
   \item Internationalization\index{Internationalization} chosen by the user may require different processing.
2932
   \item Quoted\index{quoted strings} strings should not be changed to upper or lowercase\index{lowercase} (by APQ).
2933
\end{enumerate}
2934
2935
The Append\_Quoted\index{Append\_Quoted} procedure call is designed to make it easier for
2936
the programmer to supply a string value that may contain special characters
2937
within it. Since a string value is already supplied by APQ with outer\index{outer quotes}
2938
quotes, any quote\index{quote} appearing within the string must be quoted. The
2939
Append\_Quoted procedure provides the necessary outer quotes\index{quotes}
2940
for the sring value and escapes\index{escapes} any special characters\index{special characters}
2941
occuring within it as well. 
2942
2943
Another very important reason for using this API call for quoted strings
2944
is that this will prevent the APQ library from changing the case of\index{case of SQL}
2945
any SQL text that is created. This is true no matter what the current
2946
SQL case policy\index{case policy} is (see type APQ\-.SQL\-\_Case\-\_Type on page \pageref{SQL_Case_Type Choices}).
2947
Any string segment\index{string segment} that was added to the query with this API call
2948
will not have its case changed when the query is executed or the text
2949
of the SQL is returned in a call to the To\_String\index{To\_String} function.
2950
2951
There are two Append\_Quoted procedures, which differ only in the data
2952
type of the \emph{SQL} argument:
2953
2954
\begin{Code}
2955
procedure Append_Quoted(
2956
   Q :          in out Query_Type;
2957
   Connection : in out Root_Connection_Type'Class;
2958
   SQL :        in     String;
2959
   After :      in     String := ""
2960
);
2961
\end{Code}
2962
2963
\begin{Code}
2964
procedure Append_Quoted(
2965
   Q :          in out Query_Type;
2966
   Connection : in out Root_Connection_Type'Class;
2967
   SQL :        in     Ada.Strings.Unbounded.Unbounded_String;
2968
   After :      in     String := ""
2969
);
2970
\end{Code}
2971
2972
Notice that this particular API call requires a connection\index{connection}. The reason
2973
for this is that some databases require the server to make the appropriate
2974
choices dealing with internationalized\index{internationalized} character sets\index{character sets}. The quoting\index{quoting}
2975
conventions also vary from database to database, so APQ relies upon
2976
the database vendor software to perform the quoting for you.
2977
2978
The following example illustrates the use of this call (using the
2979
String type):
2980
2981
\begin{Example}
2982
declare
2983
   C :               Connection_Type;
2984
   Q :               Query_Type;
2985
   Freds_Emporium :  String := "Fred's Emporium";
2986
begin
2987
   ...
2988
   Prepare(Q,    "SELECT COMPNO,COMPANY_NAME");
2989
   Append_Line(Q,"FROM SUPPLIER");
2990
   Append(Q,     "WHERE COMPANY_NAME = ");
2991
   Append_Quoted(Q,C,Freds_Emporium,New_Line);
2992
\end{Example}
2993
2994
The effect of these calls is to build an SQL query\index{SQL} that looks as follows
2995
(for PostgreSQL\index{PostgreSQL}):
2996
2997
\begin{SQL}
2998
SELECT COMPNO,COMPANY_NAME
2999
FROM SUPPLIER
3000
WHERE COMPANY_NAME = 'Fred\'s Emporium'
3001
\end{SQL}
3002
3003
Notice how the quote character was escaped for use by the PostgreSQL\index{PostgreSQL}
3004
database server. Note also that even though the SQL case policy\index{case policy} was to
3005
use Upper\_Case\index{Upper\_Case}, the case of the quoted text was preserved.
3006
3007
APQ will automatically adjust the quoting conventions\index{quoting conventions} to match the
3008
database being used. The same example above when used for Sybase\index{Sybase},
3009
would produce the following SQL text\index{SQL text} instead:
3010
3011
\begin{SQL}
3012
SELECT COMPNO,COMPANY_NAME
3013
FROM SUPPLIER
3014
WHERE COMPANY_NAME = 'Fred''s Emporium'
3015
\end{SQL}
3016
3017
Sybase uses a doubled-up quote\index{doubled-up quote} instead.
3018
3019
Using APQ's Append\_Quoted frees the programmer from worrying about
3020
quoting conventions and guarantees that the case of the text will be
3021
preserved.
3022
3023
\subsection{Append Non-String Types to SQL Query}
3024
3025
A fairly large set of builtin non-string\index{non-string types} data types are supported by varied
3026
Append calls that differ in the second argument V. The following
3027
is a list of their specifications:
3028
3029
\begin{Code}
3030
procedure Append(
3031
   Q :     in out Query_Type;
3032
   V :     in     APQ_Boolean;
3033
   After : in     String := ""
3034
);
3035
\end{Code}
3036
3037
\begin{Code}
3038
procedure Append(
3039
   Q :     in out Query_Type;
3040
   V :     in     APQ_Date;
3041
   After : in     String := ""
3042
);
3043
\end{Code}
3044
3045
\begin{Code}
3046
procedure Append(
3047
   Q :     in out Query_Type;
3048
   V :     in     APQ_Time;
3049
   After : in     String := ""
3050
);
3051
\end{Code}
3052
3053
\begin{Code}
3054
procedure Append(
3055
   Q :     in out Query_Type;
3056
   V :     in     APQ_Timestamp;
3057
   After : in     String := ""
3058
);
3059
\end{Code}
3060
3061
\begin{Code}
3062
procedure Append(
3063
   Q :     in out Query_Type;
3064
   V :     in     APQ_Bitstring;
3065
   After : in     String := ""
3066
);
3067
\end{Code}
3068
3069
\begin{Code}
3070
procedure Append(
3071
   Q :     in out Query_Type;
3072
   V :     in     Row_ID_Type;
3073
   After : in     String := ""
3074
);
3075
\end{Code}
3076
3077
These Append\index{Append} procedure calls automatically convert\index{convert} the supplied data
3078
type in argument V, internally into a string\index{string} using the To\_String\index{To\_String} function
3079
appropriate to the data type. Internally, the string Append procedure
3080
is then utilized to perform the remaining work. The following example
3081
illustrates their use:
3082
3083
\begin{Example}
3084
declare
3085
   Q :         Query_Type;
3086
   Ship_Date : APQ_Date;
3087
begin
3088
   ...
3089
   Prepare(Q,    "SELECT COMPNO,COMPANY_NAME,SHIP_DATE");
3090
   Append_Line(Q,"FROM SUPPLIER");
3091
   Append(Q,     "WHERE SHIP_DATE = ");
3092
   Append(Q,Ship_Date,New_Line);
3093
\end{Example}
3094
3095
The example presented builds an SQL query that looks like this:
3096
3097
\begin{SQL}
3098
SELECT COMPNO,COMPANY_NAME,SHIP_DATE
3099
FROM SUPPLIER
3100
WHERE SHIP_DATE = '2002-07-21'
3101
\end{SQL}
3102
3103
Notice that the Append call for APQ\_Date\index{APQ\_Date} automatically supplies the
3104
necessary quotes to the SQL query\index{SQL query} (if needed for the database being
3105
used). All of the data types supported are molded into a format that
3106
is acceptable in the native database SQL syntax\index{SQL syntax}. 
3107
3108
There is one additional Append procedure call that has a special set
3109
of arguments in order to support dates\index{dates} with time zones\index{time zones}. The arguments
3110
for this procedure call are as follows:
3111
3112
\begin{Code}
3113
procedure Append(
3114
   Q :     in out Query_Type;
3115
   TS :    in     APQ_Timestamp;
3116
   TZ :    in     APQ_Timezone;
3117
   After : in     String := ""
3118
);
3119
\end{Code}
3120
3121
Apart from the different argument names TS and TZ, this
3122
procedure works in the same fashion as the former Append\index{Append} procedure
3123
call. The TZ argument simply supplies the additional time zone\index{time zone}
3124
information to be added to the timestamp\index{timestamp}.
3125
3126
\begin{description}
3127
\item [Note:] Not all databases support the use of timezone values.
3128
\end{description}
3129
3130
\subsection{Generic Append SQL Procedures}
3131
3132
Ada programmers often take advantage of the strong typing \index{strong typing}that
3133
is available in the language. To accomodate this programming aspect,
3134
generic procedures are available so that type conversions\index{type conversions}
3135
are unnecessary. The following table documents the generic procedures
3136
that accept one generic argument named Val\_Type and the data
3137
types that they support:
3138
3139
\begin{Code}
3140
generic
3141
   type Val_Type is new Boolean;
3142
procedure Append_Boolean(
3143
   Q :     in out Root_Query_Type'Class;
3144
   V :     in     Val_Type;
3145
   After : in     String := ""
3146
);
3147
\end{Code}
3148
3149
\begin{Code}
3150
generic
3151
   type Val_Type is range <>;
3152
procedure Append_Integer(
3153
   Q :     in out Root_Query_Type'Class;
3154
   V :     in     Val_Type;
3155
   After : in     String := ""
3156
);
3157
\end{Code}
3158
3159
\begin{Code}
3160
generic
3161
   type Val_Type is mod <>;
3162
procedure Append_Modular(
3163
   Q :     in out Root_Query_Type'Class;
3164
   V :     in     Val_Type;
3165
   After : in     String := ""
3166
);
3167
\end{Code}
3168
3169
\begin{Code}
3170
generic
3171
   type Val_Type is digits <>;
3172
procedure Append_Float(
3173
   Q :     in out Root_Query_Type'Class;
3174
   V :     in     Val_Type;
3175
   After : in     String := ""
3176
);
3177
\end{Code}
3178
3179
\begin{Code}
3180
generic
3181
   type Val_Type is delta <>;
3182
procedure Append_Fixed(
3183
   Q :     in out Root_Query_Type'Class;
3184
   V :     in     Val_Type;
3185
   After : in     String := ""
3186
);
3187
\end{Code}
3188
3189
\begin{Code}
3190
generic
3191
   type Val_Type is delta <> digits <>;
3192
procedure Append_Decimal(
3193
   Q :     in out Root_Query_Type'Class;
3194
   V :     in     Val_Type;
3195
   After : in     String := ""
3196
);
3197
\end{Code}
3198
3199
\begin{Code}
3200
generic
3201
   type Val_Type is new Ada.Calendar.Time;
3202
procedure Append_Date(
3203
   Q :     in out Root_Query_Type'Class;
3204
   V :     in     Val_Type;
3205
   After : in     String := ""
3206
);
3207
\end{Code}
3208
3209
\begin{Code}
3210
generic
3211
   type Val_Type is new Ada.Calendar.Day_Duration;
3212
procedure Append_Time(
3213
   Q :     in out Root_Query_Type'Class;
3214
   V :     in     Val_Type;
3215
   After : in     String := ""
3216
);
3217
\end{Code}
3218
3219
\begin{Code}
3220
generic
3221
   type Val_Type is new APQ_Timestamp;
3222
procedure Append_Timestamp(
3223
   Q :     in out Root_Query_Type'Class;
3224
   V :     in     Val_Type;
3225
   After : in     String := ""
3226
);
3227
\end{Code}
3228
3229
\begin{Code}
3230
generic
3231
   type Val_Type is new APQ_Bitstring;
3232
procedure Append_Bitstring(
3233
   Q :     in out Root_Query_Type'Class;
3234
   V :     in     Val_Type;
3235
   After : in     String := ""
3236
);
3237
\end{Code}
3238
3239
Each of the resulting instantiated procedures provide the following
3240
calling signature:
3241
3242
\begin{Code}
3243
procedure Append(
3244
   Q :     in out Query_Type;
3245
   V :     in     Val_Type;
3246
   After : in     String := ""
3247
);
3248
\end{Code}
3249
3250
The following code fragment illustrates how these are instantiated\index{instantiated} and used:
3251
3252
\begin{NumberedExample}
3253
declare
3254
   type Price_Type is delta 0.01 digits 12;\label{Ex:TypeDef}
3255
   procedure Append is new Append_Decimal(Price_Type);\label{Ex:Inst}
3256
3257
   Q :             Query_Type;
3258
   Selling_Price : Price_Type;
3259
begin
3260
   ...
3261
   Prepare(Q,"UPDATE SUPPL_ORDER");
3262
   Append(Q."SET SELLING_PRICE = ");
3263
   Append(Q,Selling_Price,New_Line);\label{Ex:InstUse}
3264
   Append_Line(Q,"WHERE ...");
3265
\end{NumberedExample}
3266
3267
In this example, the application defines its own type Price\_Type
3268
in line~\ref{Ex:TypeDef}. After instantiating the Append\_Decimal
3269
generic procedure as Append\index{Append} (line~\ref{Ex:Inst}), the application is
3270
free to neatly append a price value from Selling\_Price in
3271
line~\ref{Ex:InstUse}, as if it were natively supported.
3272
3273
3274
\subsection{Generic Append\_Timezone}
3275
3276
The Append\_Timezone\index{Append\_Timezone} has an additional generic paramter. The instantiated\index{instantiated}
3277
procedure also has a slightly different set of calling arguments. The generic
3278
parameters are specified as follows:
3279
3280
\begin{Code}
3281
generic
3282
   type Date_Type is new Ada.Claendar.Time;
3283
   type Zone_Type is new APQ_Timezone;
3284
procedure Append_Timezone(
3285
   Q :     in out Root_Query_Type'Class;
3286
   V :     in     Date_Type;
3287
   Z :     in     Zone_Type;
3288
   After : in     String := ""
3289
);
3290
\end{Code}
3291
3292
The instantiated procedure has the following calling signature:
3293
3294
\begin{Code}
3295
procedure Append(
3296
   Q :     in out Root_Query_Type'Class;
3297
   V :     in     Date_Type;
3298
   Z :     in     Zone_Type;
3299
   After : in     String := ""
3300
);
3301
\end{Code}
3302
3303
The following shows an example of its use:
3304
3305
\begin{NumberedExample}
3306
declare
3307
   type Ship_Date_Type is new APQ_Timestamp;
3308
   type Ship_Zone_Type is new APQ_Timezone;
3309
3310
   procedure Append is new Append_Timezone(\label{Ex:InstTZ}
3311
      Ship_Date_Type,Ship_Zone_Type);
3312
3313
   Q :         Query_Type;
3314
   Ship_Date : Ship_Date_Type;
3315
   Ship_Zone : Ship_Zone_Type;
3316
begin
3317
   ...
3318
   Prepare(Q,"SELECT COUNT(*)");
3319
   Append_Line(Q,"FROM ORDER");
3320
   Append(Q,"WHERE SHIP_DATE = ");
3321
   Append(Q,Ship_Date,Ship_Zone,New_Line);\label{Ex:UseInstTZ}
3322
   ...
3323
\end{NumberedExample}
3324
3325
The example shows how the application's types Ship\_Date\_Type
3326
and Ship\_Zone\_Type are accomodated by the Append\index{Append} instantiation\index{instantiation}
3327
of the generic procedure (line~\ref{Ex:InstTZ}). The instantiated
3328
Append routine is applied in line~\ref{Ex:UseInstTZ}.
3329
3330
3331
\subsection{Generic Append of Bounded SQL Text}
3332
3333
To accomodate the use of the package Ada\-.Strings\-.Bounded\index{Ada.Strings.Bounded},
3334
the generic procedure Append\_Bounded\index{Append\_Bounded} was provided. Its instantiation
3335
requirements differ from the preceeding ones because the instantiation
3336
of the Bounded\_String\index{Bounded\_String} type must be provided to the Append\_Bounded
3337
generic procedure. The generic procedure is defined as follows:
3338
3339
\begin{Code}
3340
generic
3341
   with package P 
3342
      is new Ada.Strings.Bounded.Generic_Bounded_Length(<>);
3343
procedure Append_Bounded(
3344
   Q :     in out Query_Type;
3345
   SQL :   in     P.Bounded_String;
3346
   After : in     String
3347
);
3348
\end{Code}
3349
3350
In other words, Append\_Bounded can be instantiated from any instantiation
3351
of the Ada.Strings.Bounded.Generic\_Bounded\_Length package. The following
3352
example makes this easier to understand:
3353
3354
\begin{NumberedExample}
3355
with Ada.Strings.Bounded;
3356
...
3357
declare
3358
   package B80 
3359
      is new Ada.Strings.Bounded.Generic_Bounded_Length(80);
3360
   package B20 
3361
      is new Ada.Strings.Bounded.Generic_Bounded_Length(20);
3362
3363
   procedure Append is new Append_Bounded(B80);\label{Ex:B80}
3364
   procedure Append is new Append_Bounded(B20);\label{Ex:B20}
3365
3366
   Q :         Query_Type;
3367
   Item_Code : B20;
3368
   Item_Name : B80;
3369
begin
3370
   ...
3371
   Prepare(Q,    "SELECT COUNT(*)");
3372
   Append_Line(Q,"FROM ORDER");
3373
   Append(Q,     "WHERE ITEM_CODE = ","'");
3374
   Append(Q,Item_Code,"' AND ITEM_NAME = '");\label{Ex:UseB20}
3375
   Append(Q,Item_Name,"'" & New_Line);\label{Ex:UseB80}
3376
   ...
3377
\end{NumberedExample}
3378
3379
The example shows how two different generic procedures named Append
3380
are instantiated from the Bounded\_String instantiations B80 (line~\ref{Ex:B80})
3381
and B20 (line~\ref{Ex:B20}). Note that the Append\_Bounded procedure does not escape
3382
special characters, nor provide the outer quotes (this is a poor example of its
3383
use actually).
3384
3385
The Append\index{Append} call used in line~\ref{Ex:UseB20} is the one that was
3386
instantiated on line~\ref{Ex:B20}. The other Append used on
3387
line~\ref{Ex:UseB80} was instantiated on line~\ref{Ex:B80}. These
3388
are matched according to the normal Ada95\index{Ada95} argument type matching
3389
rules.
3390
3391
\subsection{Generic Append\_Bounded\_Quoted Procedure}
3392
3393
To accomodate the quoting needs of Bounded\_Strings, the Append\_Bounded\_Quoted\index{Append\_Bounded\_Quoted}
3394
generic procedure may be used:
3395
3396
\begin{Code}
3397
generic
3398
   with package P
3399
      is new Ada.Strings.Bounded.Generic_Bounded_Length(<>);
3400
procedure Append_Bounded_Quoted(
3401
   Q :     in out Query_Type;
3402
   C :     in     Connection_Type;
3403
   SQL :   in     P.Bounded_String;
3404
   After : in     String
3405
);
3406
\end{Code}
3407
3408
It is otherwise very similar to the previous Append\_Unbounded\index{Append\_Unbounded} procedure.
3409
The following example illustrates a safer\index{safer} version of the prior example:
3410
3411
\begin{Example}
3412
with Ada.Strings.Bounded;
3413
...
3414
declare
3415
   package B80 
3416
      is new Ada.Strings.Bounded.Generic_Bounded_Length(80);
3417
   package B20 
3418
      is new Ada.Strings.Bounded.Generic_Bounded_Length(20);
3419
3420
   procedure Append_Quoted is new Append_Bounded_Quoted(B80);
3421
   procedure Append_Quoted is new Append_Bounded_Quoted(B20);
3422
3423
   C :         Connection_Type;
3424
   Q :         Query_Type;
3425
   Item_Code : B20;
3426
   Item_Name : B80;
3427
begin
3428
   ...
3429
   Prepare(Q,    "SELECT COUNT(*)");
3430
   Append_Line(Q,"FROM ORDER");
3431
   Append(Q,     "WHERE ITEM_CODE = ");
3432
   Append_Quoted(Q,C,Item_Code," AND ITEM_NAME = ");
3433
   Append_Quoted(Q,C,Item_Name,New_Line);
3434
   ...
3435
\end{Example}
3436
3437
The instantiations of Append\_Quoted\index{Append\_Quoted}%
3438
\footnote{It is not necessary to instantiate these procedures as
3439
Append\_Quoted, but it is recommended for readability.} here will
3440
properly escape\index{escape} any special\index{special characters} characters that may appear in the program's
3441
string variables Item\_Code and Item\_Name. Additionally, note that the
3442
outer quotes\index{quotes} are provided automatically, easing the programmer's burden
3443
in building up the SQL query. Like other Append\_Quoted API calls within
3444
APQ, the case\index{case within quoted strings} within quoted strings is always preserved.
3445
3446
3447
\subsection{Encoding Quoted Strings}
3448
3449
While strings are well covered by the category 1 support, it is necessary
3450
to encode a NULL\index{NULL} in place of a quoted string\index{quoted string},
3451
when the value is null. The generic specification for 
3452
Encode\-\_String\-\_Quoted\index{Encode\_String\_Quoted} is as follows:
3453
3454
\begin{Code}
3455
generic
3456
   type Ind_Type is new Boolean;
3457
procedure Encode_String_Quoted(
3458
   Q :          in out Root_Query_Type'Class;
3459
   Connection : in     Root_Connection_Type'Class;
3460
   SQL :        in     String;
3461
   Indicator :  in     Ind_Type;
3462
   After :      in     String := ""
3463
);
3464
\end{Code}
3465
3466
An example of its instantiation and use is shown below:
3467
3468
\begin{Example}
3469
declare
3470
   type Cust_Name_Ind_Type is new Boolean;
3471
3472
   procedure Encode_Quoted 
3473
      is new Encode_String_Quoted(Cust_Name_Ind_Type);
3474
3475
   Q :             Query_Type;
3476
   Cust_Name :     String(1..30);
3477
   Cust_Name_Ind : Cust_Name_Ind_Type; -- Indicator
3478
begin
3479
   ...
3480
   Prepare(Q,"UPDATE CUSTOMER");
3481
   Append_Line(Q,"SET CUST_NAME = ");
3482
   Encode_Quoted(Q,Cust_Name,Cust_Name_Ind);
3483
\end{Example}
3484
3485
In this example, the String Cust\_Name is given outer quotes
3486
and any special characters are escaped before the value is appended
3487
to the current SQL query being collected in object Q. If however,
3488
the indicator Cust\_Name\_Ind is True (indicating that the
3489
value Cust\_Name should be interpreted as NULL\index{NULL}), then the string
3490
``NULL'' is appended instead. When NULL is supplied, no outer
3491
quotes are supplied. Th