-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrwug7.tex
1016 lines (823 loc) · 33.6 KB
/
rwug7.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\chapter{Persistent Data Storage}
This chapter describes the interface between SQL (structured query
language) and RuleWorks. The SQL interface allows you easily to read
data from a database into RuleWorks working memory, and write values
from working memory into a database.
\begin{note}
In the current version of RuleWorks, the only supported database is
VAX Rdb/VMS.
\end{note}
This chapter covers the following topics:
\begin{itemize}
\item SQL Expression Syntax
\item Mapping Data to Working Memory Objects
\item Linking with the SQL Libraries
\item Attaching to a Database
\item Starting an SQL Transaction
\item Reading from a Database
\item Using Database Key Values
\item Writing to a Database
\item Error Handling
\item Ending an SQL Transaction
\item Detaching from a Database
\end{itemize}
We assume that you are familiar with SQL concepts and statements. If
not, please refer to the VAX Rdb/VMS documentation, especially the
\emph{DEC Rdb Introduction to SQL} and the \emph{DEC Rdb Guide to SQL
Programming}.
\section{SQL Expression Syntax}
The SQL interface consists of a set of RHS actions that generate the
appropriate dynamic SQL statements (see Table~\ref{t:7-1}). The
arguments to the RHS actions are passed to the SQL statements
unchanged. For example, the following RuleWorks action:
\begin{quote}
\begin{verbatim}
(sql-fetch-as-object select field1, field2
from table1 where field1 < field2)
\end{verbatim}
\end{quote}
generates the following dynamic SQL statement:
\begin{quote}
\begin{verbatim}
SELECT FIELD1, FIELD2 FROM TABLE1 WHERE FIELD1 < FIELD2
\end{verbatim}
\end{quote}
Note that the select expression must start with \co{SELECT} spelled
out in full, not abbreviated.
\begin{table}
\begin{tabularx}{\columnwidth}{XXX}
\toprule
RHS Action & SQL Statement & Description \\
\midrule
\raggedright
\co{SQL-ATTACH} \it{database-spec} [\it{dbkey-scope}]
&
\co{DECLARE SCHEMA} \it{database-spec}
&
Specifies the database that is
to be accessed
by the other RuleWorks SQL DBKEY SCOPE IS
dbkey-scope actions. \\\addlinespace
\co{SQL-COMMIT}
&
\co{COMMIT}
&
Completes the current SQL
transaction and makes permanent
any changes made during the
transaction. \\\addlinespace
\raggedright
\co{SQL-DELETE} \it{table-name} [\it{where-clause}]
& \raggedright\co{DELETE FROM} \it{table-name} \it{where-clause}
& Deletes specified records from the database. \\\addlinespace
\co{SQL-DETACH}
& \co{FINISH}
& Commits any outstanding transaction and detaches from the database. \\\addlinespace
\raggedright
\verb|SQL-FETCH-EACH| \verb|<|\it{var}\verb|>| \ldots \it{select-expr}
(\it{RHS-action}) \ldots & \it{select-expr}
& Binds field values to
RuleWorks variables
and executes RuleWorks actions
that can
use those variables. \\\addlinespace
\co{SQL-FETCH-AS-OBJECT} \it{select-expr}
& \it{select-expr}
& Makes WMOs from database records. \\\addlinespace
\raggedright
\co{SQL-INSERT} \it{table-name} \it{sql-expr}
& \raggedright\co{INSERT INTO} \it{table-name} \it{sql-expr}
& Stores new records in the database. \\\addlinespace
\verb|SQL-INSERT-FROM-OBJECT| \verb|<$|\it{id-var}\verb|>| &
SQL-INSERT-INTO table-name (field-names)
SQL-INSERT-INTO )VALUES (field-values)
& Stores the contents of a WMO in a
new database record. \\\addlinespace
\co{SQL-ROLLBACK} & \co{ROLLBACK} & Completes the current SQL
and undoes any changes made during
the
transaction. \\\addlinespace
\co{SQL-START} [\it{txn-options}] &
\raggedright
\co{SET TRANSACTION} \it{txn-options}
& Starts an SQL
transaction and sets
transaction
options. \\\addlinespace
\raggedright
\co{SQL-UPDATE-FROM-OBJECT} \verb|<$|\it{id-var}\verb|>|
[\it{where-clause}] &
\raggedright
\co{UPDATE} \it{table-name} \it{set-clause} \it{where-clause}
& Modifies existing database
records, using the contents of a WMO. \\
\bottomrule
\end{tabularx}
\caption{SQL Statements Generated by RuleWorks Actions}
\label{t:7-1}
\end{table}
\subsection{Using Vertical Bars}
To make the process more efficient, you can use vertical bars (the
RuleWorks quote character, \verb,|,) around the atoms that are passed
to SQL. For example:
\begin{quote}
\begin{verbatim}
(sql-fetch-as-object
|select field1, field2 from table1 where field1 < field2|)
\end{verbatim}
\end{quote}
In the action above, the RuleWorks parser makes a single atom out of
the entire select expression. The same length restrictions apply to
quoted atoms in select expressions as in other RuleWorks code (see
Chapter~\ref{c:workingmem}). You cannot use vertical bars around a
multiline SQL expression; you must use a pair of vertical bars for
each line. For example:
\begin{quote}
\begin{verbatim}
(sql-fetch-as-object |select field1, field2|
|from table1|
|where field1 < field2|)
\end{verbatim}
\end{quote}
Vertical bars are required in the following circumstances:
\begin{itemize}
\item When the information to be passed to SQL is case
sensitive. RuleWorks automatically converts unquoted atoms to
uppercase.
\item When the information to be passed to SQL includes parentheses
\verb|()|. For example, this RHS action:
\begin{quote}
\begin{verbatim}
(sql-insert table1 |(field1) values (|'text'|)|)
\end{verbatim}
\end{quote}
generates this SQL statement:
\begin{quote}
\begin{verbatim}
INSERT INTO TABLE1 (field1) values ('text')
\end{verbatim}
\end{quote}
\end{itemize}
\subsection{Using Variables}
Variables must be surrounded by white space to allow the RuleWorks
parser to recognize them as variables. A variable name followed
immediately by a comma looks to the parser like an atom instead of a
variable to be evaluated. In the following example:
\begin{quote}
\begin{verbatim}
<var1>, <var2>
\end{verbatim}
\end{quote}
the RuleWorks parser treats \verb|<VAR1>,| as a symbol and
\verb|<VAR2>| as a variable. The next example:
\begin{quote}
\begin{verbatim}
<var1> , <var2>
\end{verbatim}
\end{quote}
results in the expected behavior.
\subsection{Using Single Quotes (\co{'})}
Anything that SQL treats as a character string must be enclosed in
single quotes (\co'). This applies to both atoms and variables. Quoted
variables must have at least one white space character before the
opening quote and after the closing quote.
Quoted variables expand to the variable value surrounded by single
quotes. Quoted variables that are bound to compound values expand to
the list of compound elements surrounded by a single set of single
quotes. The elements of the compound are not quoted. For example,
assuming \verb|<COMPOUND2>| is bound to the value \co{(COMPOUND SOME
MORE TEXT)}, the following RHS argument:
\begin{quote}
\begin{verbatim}
'<compound2>'
\end{verbatim}
\end{quote}
is passed to SQL as the literal:
\begin{quote}
\begin{verbatim}
'SOME MORE TEXT'
\end{verbatim}
\end{quote}
\subsection{SQL Data Types}
The following table shows the mapping between SQL and RuleWorks data
types:
\begin{center}
\begin{tabular}{ll}
\toprule
SQL Data Type & Converted to RuleWorks Data Type \\
\midrule
\co{CHAR} & \co{SYMBOL} \\
\co{VARCHAR} & \co{SYMBOL} \\
\co{SMALLINT} & \co{INTEGER} \\
\co{INTEGER} & \co{INTEGER} \\
\co{QUADWORD} & \co{SYMBOL} \\
\co{FLOAT} & \co{FLOAT} \\
\co{DOUBLE} & \co{FLOAT} \\
\co{DATE} & \co{SYMBOL} \\
\bottomrule
\end{tabular}
\end{center}
RuleWorks has no way to represent double-precision floating-point
numbers or integers larger than 32 bits.
\subsection{Examples of SQL Expressions}
This section contains further examples of RHS actions and the SQL
statements they generate. All the examples in this section assume the
following variable bindings:
\begin{center}
\begin{tabular}{ll}
\toprule
Variable & Value Bound to \\
\midrule
\verb|<simple1>| & \co{SELECT} \\
\verb|<simple2>| & \co{10} \\
\verb|<simple3>| & \verb,| 'text' |, \\
\verb|<simple4>| & \co{TEXT} \\
\verb|<compound1>| & \co{(COMPOUND SELECT * FROM W2 WHERE SI = 10)} \\
\verb|<compound2>| & \co{(COMPOUND SOME MORE TEXT)} \\
\bottomrule
\end{tabular}
\end{center}
In the following example, six actions are
equivalent, but the second is the most efficient:
\begin{exampl}[SQL Expression---Equivalent Actions]
\begin{verbatim}
(sql-fetch-as-object select * from w2 where si = 10)
(sql-fetch-as-object |SELECT * FROM W2 WHERE SI = 10|)
(sql-fetch-as-object select * from w2 where si = <simple2>)
(sql-fetch-as-object <simple1> * from w2 where si = <simple2>)
(sql-fetch-as-object <simple1> |* FROM W2 WHERE SI =| <simple2>)
(sql-fetch-as-object <compound1>)
\end{verbatim}
\vspace{1ex}
The SQL statement generated by the above six actions is shown below:
\begin{verbatim}
SELECT * FROM W2 WHERE SI = 10
\end{verbatim}
\end{exampl}
\begin{exampl}[SQL Expression---Insert Into Table]
\begin{verbatim}
(sql-insert table-name |(field1) VALUES (| <simple3> |)|)
INSERT INTO TABLE-NAME (field1) VALUES ( 'text' )
\end{verbatim}
\end{exampl}
\begin{exampl}[SQL Expression---Insert Table Name]
\begin{verbatim}
(sql-insert table-name (field1) values ( <simple2> ))
\end{verbatim}
\vspace{1ex}
The RuleWorks parser stops at the unquoted parentheses and does not
generate any SQL statement.
\end{exampl}
\begin{exampl}[SQL Expression---Insert Text Into Table Name]
\begin{verbatim}
(sql-insert table-name |(field1) VALUES (| <simple3> '<simple4>' |)|)
INSERT INTO TABLE-NAME (field1) VALUES ('text' 'TEXT')
\end{verbatim}
\end{exampl}
\begin{exampl}[SQL Expression---Insert More Text Into Table Name]
\begin{verbatim}
(sql-insert table-name |(field1, field2, field3, field4)| -
|VALUES (10, 'text','TEXT', 'SOME MORE TEXT')|)
INSERT INTO TABLE-NAME (field1, field2, field3, field4)
VALUES (10, 'text','TEXT', 'SOME MORE TEXT')
\end{verbatim}
\end{exampl}
Note that the RuleWorks-SQL interface does not actually generate
multiline statements containing continuation characters (\co-). Multiline
statements are shown here for clarity of the examples..
\begin{exampl}[SQL Expression---Multiline Statements]
\begin{verbatim}
(sql-insert table-name
|(FIELD1, FIELD2, FIELD3, FIELD4) VALUES (|
<simple2> , <simple3> , '<simple4>' ,
'<compound2>' |)|)
INSERT INTO TABLE-NAME (FIELD1, FIELD2, FIELD3, FIELD4) -
VALUES ( 10 , 'text' , 'TEXT' , 'SOME MORE TEXT' )
\end{verbatim}
\end{exampl}
This SQL action is the same as in the above example, except for the
lack of white space between the variables and the commas. RuleWorks
does not report any errors in the action below, but passes symbols to
SQL rather than values:
\begin{exampl}[SQL Expression---Passing Symbols to SQL]
\begin{verbatim}
(sql-insert table-name
|(FIELD1, FIELD2, FIELD3, FIELD4) VALUES (|
<simple2>, <simple3>, '<simple4>',
'<compound2>' |)|)
INSERT INTO TABLE-NAME (FIELD1, FIELD2, FIELD3, FIELD4) -
VALUES ( <SIMPLE2>, <SIMPLE3>, '<SIMPLE4>', -
'SOME MORE TEXT' )
\end{verbatim}
\end{exampl}
If SQL detects an error in the generated SQL statement, the interface
creates an instance of class
\verb|SQL$MSG|. See the section of this chapter, Error Handling, for
details on message WMOs.
\section{Mapping Data to Working Memory Objects}
The fetch, insert, and update actions come in two forms: simple and
flexible. The simple forms require a one-to-one mapping between object
class names and database table names, and between attribute names and
database field names. The flexible forms have no mapping requirement.
\subsection{One-to-One Mappings}
The simple forms of the SQL fetch, insert, and update actions are
listed below:
\begin{itemize}
\item \co{SQL-FETCH-AS-OBJECT}
\item \co{SQL-INSERT-FROM-OBJECT}
\item \co{SQL-UPDATE-FROM-OBJECT}
\end{itemize}
The syntax for these actions is much simpler than the syntax for the
flexible SQL actions, because an automatic mapping from WMOs to SQL
records is performed. There must be a database table name that exactly
matches the object class name; there must also be some database field
names that match attribute names. A one-to-one correspondence is shown
in the following comparison of an \co{OBJECT-CLASS} declaration in
RuleWorks and a \co{CREATE TABLE} statement in SQL:
\begin{center}
\begin{tabular}{ll}
\toprule
RuleWorks & SQL \\
\midrule
\co{(object-class part} & \co{create table part} \\
\qquad\verb|^partnumber| & \qquad\co{(partnumberchar (10),} \\
\qquad\verb|^name| & \qquad\co{ namechar (63),} \\
\qquad\verb|^price)| & \qquad\co{ price double)} \\
\bottomrule
\end{tabular}
\end{center}
The following simple fetch action is based on the declaration and
statement shown above:
\begin{exampl}[Fetch Action]
\begin{verbatim}
; to fetch a particular part number
; the part number is the symbolic value bound to <my-part>
(sql-fetch-as-object select * from part
where partnumber = '<my-part>')
\end{verbatim}
\end{exampl}
Exceptions to the one-to-one correspondence can be achieved easily by
defining a view of the database, or by using more complex SQL select
expressions. Note however that updates or inserts to multitable views
are not supported. (See the section of this chapter titled, Using
Views to Fetch Data, for more information on views.)
You can have more attributes in the object class than fields in the
database table, or more fields than attributes. The simple fetch
action, \co{SQL-FETCH-AS-OBJECT}, ignores fields that do not correspond to
attributes. Attributes that do not correspond to fields are given
their default value, if any, or the atom \co{NIL}. Similarly, the simple
insert action \co{SQL-INSERT-FROM-OBJECT} ignores attributes that do not
correspond to fields. Database fields that do not correspond to
attributes are set to their default value, if any, or to ``missing.''
The SQL interface preserves ``missing'' database field values. When
\co{SQL-FETCH-AS-OBJECT} makes an object from a database table that
has ``missing'' field values, it sets the corresponding attribute
values to \co{NIL}. Conversely, when \co{SQL-INSERT-FROM-OBJECT} makes
a database record from an object that has \co{NIL} attribute values,
it sets the corresponding field values to ``missing'' (\co{NULL}).
That is, \co{NIL} maps to ``missing'' in both directions, even if the
\co{NIL} attribute value was explicitly set.
\begin{note}
Data values for the \verb|^$ID| and \verb|^$INSTANCE-OF| attributes
are not written to the database by \co{SQL-INSERT-FROM-OBJECT}, even if
the database explicitly provides fields with these names.
\end{note}
The RuleWorks SQL interface does not automatically handle the built-in
attributes \verb|^$ID| and \verb|^$INSTANCE-OF|. Values of type
\co{INSTANCE-ID} can be written to database fields, but the SQL
interface does not guarantee consistent pointers to objects. You can
work around this restriction by using the
\verb|rul_start_id_translation| and \verb|rul_end_id| translation
run-time library routines.
The SQL interface does not recognize class inheritance. For example, a
subclass cannot be passed to \co{SQL-INSERT-FROM-OBJECT} for a table
that matches a parent class. The table name must be the same as the
value of the \verb|^$INSTANCE-OF| attribute.
\subsection{Flexible Mappings}
The flexible SQL fetch, insert, and update actions allow you to
specify particular database tables or fields that do not necessarily
correspond to object class or attribute names. The flexible actions
are listed below:
\begin{itemize}
\item \co{SQL-FETCH-EACH}
\item \co{SQL-INSERT}
\item \co{SQL-UPDATE}
\end{itemize}
\section{Linking with the SQL Libraries}
You must link your RuleWorks application with the SQL library in order
to use the SQL actions. The easiest way is to define a logical name to
point to the SQL library. For example:
\begin{quote}
\begin{verbatim}
$ DEFINE LNK$LIBRARY SYS$LIBRARY:SQL$USER
$ LINK MY_FILE, RUL$LIBRARY:RUL_TRL/LIB
\end{verbatim}
\end{quote}
(See the \emph{DEC rdb Introduction to SQL} for more information on
the SQL library.)
\section{Attaching to a Database}
Before your first database transaction, you must specify which
database you want to access. You do this with an \co{SQL-ATTACH} action,
which executes a \co{DECLARE SCHEMA} statement.
The syntax of the \co{SQL-ATTACH} action is show below:
\co{SQL-ATTACH} \it{database-spec} [\it{DBKEY-scope}]
The \it{database-spec} argument identifies which database you want to
access. This argument can be either the filename of the Rdb database
file, or the pathname of the CDD schema source. If you specify a
filename, you can use the optional keyword \co{FILENAME}. If you specify a
pathname, you must use the \co{PATHNAME} keyword. You can use a logical
name in either case. For example:
\begin{quote}
\begin{verbatim}
(sql-attach my_sql_db) ;logical name for DBDISK:[DATABASE]MY_DB.RDB
(sql-attach pathname rul_db) ;logical name for CDD$TOP.DEPT3.PERSONNEL
\end{verbatim}
\end{quote}
The optional \it{DBKEY-scope} argument can be either \co{TRANSACTION}
or \co{ATTACH}.
\begin{note}
You can access only one database at a time. Simultaneous access to
multiple databases is not supported in the RuleWorks SQL
interface.
\end{note}
You can sequentially access multiple databases in one RuleWorks
program execution.
If \co{SQL-ATTACH} is executed while a database is already attached, the
original attachment is terminated and the new database is attached
(unless a transaction is active, in which case a warning WMO is made
and the second attachment is not performed).
\section{Starting an SQL Transaction}
In RuleWorks, explicitly starting an SQL transaction is optional if
you are only going to read from the database; it is required if you
are going to write to the database. The syntax for the \co{SQL-START}
action is shown below:
\begin{quote}
\co{SQL-START} [\it{txn-options}]
\end{quote}
The \it{txn-options} argument is optional: its default value is
\co{READ ONLY}. This argument can include any transaction option that
is valid in a \co{SET TRANSACTION} statement. For example:
\begin{quote}
\begin{verbatim}
(sql-start read write reserving table_1 for shared read)
\end{verbatim}
\end{quote}
If a transaction is not currently active when a fetch action is
executed, SQL implicitly starts a \co{READ ONLY} transaction. The
interface ends this transaction immediately after the fetch is
completed.
\section{Reading from a Database}
The RuleWorks SQL interface provides two ways to read (fetch) data
from a database. The simple form, \co{SQL-FETCH-AS-OBJECT}, automatically
makes new objects from selected database records.
The flexible form, \co{SQL-FETCH-EACH}, binds the values in selected
database records to variables that can then be used in whatever RHS
actions you specify.
Both forms of the fetch action use the SQL syntax for select
expressions. The select expression specifies which database records
are selected, and which database fields are fetched. The select
expression must be a valid one that you could put in a \co{SELECT}
statement. For example:
\begin{quote}
\begin{verbatim}
select fld1, fld2 from table_1 where fld3 > 10 and fld4 = 'abc'
select * from table_2 where fld4 = '<var>'
\end{verbatim}
\end{quote}
\begin{note}
You must put single-quote (\co') characters around nonnumeric
constants and variables. You must put at least one white space
character before the opening quote and after the closing
quote. However, you must not put any white space between the single
quotes and a variable.
\end{note}
\subsection{Using the Simple Fetch Action}
The \co{SQL-FETCH-AS-OBJECT} action automatically makes a new object
out of each selected database record. If the select expression causes
n records to be fetched from the database, then a single execution of
that \co{SQL-FETCH-AS-OBJECT} action creates n new objects. The
\co{OBJECT-CLASS} name of the new objects is the name of the database
table.
The syntax of the \co{SQL-FETCH-AS-OBJECT} action is shown below:
\begin{quote}
\co{SQL-FETCH-AS-OBJECT} \it{select-expr}
\end{quote}
The names of WMO attributes to be set by \co{SQL-FETCH-AS-OBJECT} must
match the field names of the database table (unless a view is used to
access the table, in which case it is the view's local field names
that must match the \co{OBJECT-CLASS} attribute names). For example:
\begin{quote}
\begin{verbatim}
(sql-fetch-as-object select * from part)
\end{verbatim}
\end{quote}
The example above corresponds to the \co{OBJECT-CLASS} declaration and
\co{CREATE TABLE} statement in the section of this chapter, One-to-One
Mappings.
\subsection{Using the Flexible Fetch Action}
The \co{SQL-FETCH-EACH} action binds data from selected database fields to
RuleWorks variables. You can then use these variables in RHS actions
inside the \co{SQL-FETCH-EACH} action to create or change instances of any
declared \co{OBJECT-CLASS}. If the select expression causes n records to
be fetched from the database, then the variables are bound and the RHS
actions are executed n times for a single execution of the
\co{SQL-FETCH-EACH} action.
The syntax of the \co{SQL-FETCH-EACH} action is shown below:
\begin{quote}
\co{SQL-FETCH-EACH} \co<\it{variable}\co> \ldots \co(\it{select-expr}\co)
\co(\it{RHS-action}\co) \ldots
\end{quote}
You can specify one or more variables as the first argument, but they
must not be bound prior to the \co{SQL-FETCH-EACH} action. They can be
used only in the RHS actions specified as the third argument. They
cannot be used after the \co{SQL-FETCH-EACH} action.
If you use any variables in the select expression, they must be bound
prior to the \co{SQL-FETCH-EACH} action. They can be bound on either the
LHS or RHS of the rule.
You can specify one or more \it{RHS-actions} for the third
argument. These actions can use the variables from the first argument
as well as variables bound prior to the \co{SQL-FETCH-EACH} action. If
you use a \co{BIND} action inside the \co{SQL-FETCH-EACH} action, that
variable is still bound after the action executes.
SQL interface actions are not allowed inside the \co{SQL-FETCH-EACH}
action.
\begin{exampl}[Fetching Fields from an SQL Database]
\begin{verbatim}
(rule fetch-items-from-database:software-option
(active-context ^name fetch-items-from-database)
(software-option ^$ID <the-part> ^is-expanded nil
^$INSTANCE-OF <part-type>)
-->
(sql-fetch-each <partnumber> <partname> <price> <media>
(select partnumber , name , price , media_type
from sw_part where classname = '<part-type>')
(modify <the-part>
^partnumber <partnumber>
^name <partname>
^price <price>
^media-type <media>
^is-expanded yes)))
\end{verbatim}
\end{exampl}
\co{SQL-FETCH-EACH} does tolerate a mismatch between the number of
RuleWorks variables specified in the action and the number of database
fields to be fetched for each database record. If more variables are
specified than fields fetched, the excess variables are set to
\co{NIL}; if more fields are fetched than variables specified, the
excess values are just ignored. In either case, an SQL warning WMO is
generated (see the section of this chapter, Error Handling).
Given the following \co{OBJECT-CLASS} declaration:
\begin{quote}
\begin{verbatim}
(object-class objclass ^fld1 ^fld2 ^fld3)
\end{verbatim}
\end{quote}
In terms of the WMOs created and the final binding of the variable
\verb|<FETCHED-INSTANCES>|, the following two sequences of \co{BIND}
and fetch actions are equivalent:
\begin{exampl}[Bind-Fetch Sequence]
\begin{verbatim}
(bind <fetched-instances> (compound))
(sql-fetch-each <v1> <v2> <v3>
(|select fld1, fld2, fld3 from objclass where fld4 = 10|)
(bind <instance>
(make objclass ^fld1 <v1> ^fld2 <v2> ^fld3 <v3>))
(bind <fetched-instances>
(compound <fetched-instances> <instance>)))
\end{verbatim}
\end{exampl}
If this is what is what you want to do, the second sequence is more
efficient:
\begin{exampl}[Bind-Fetch Sequence (2)]
\begin{verbatim}
(bind <fetched-instances>
(sql-fetch-as-object
|select fld1, fld2, fld3 from objclass where fld4 = 10|))
\end{verbatim}
\end{exampl}
Note however, that the \co{SQL-FETCH-EACH} action gives you more
flexibility by allowing arbitrary RHS actions (except other SQL
actions) to be performed after each fetch. Also, you are not
restricted to the one-WMO-to-one-record data model. Consider the
following actions that fetch the same data but place it into one
working memory object:
\begin{exampl}[Placing Fetch Data into One Working Memory Object (WMO)]
\begin{verbatim}
(object-class objclass
^fld1 compound
^fld2 compound
^fld3 compound)
...
(bind <fld1> (compound))
(bind <fld2> (compound))
(bind <fld3> (compound))
(sql-fetch-each <v1> <v2> <v3>
(|select fld1, fld2, fld3 from objclass where fld4 = 10|)
(bind <fld1> (compound <fld1> <v1>))
(bind <fld2> (compound <fld2> <v2>))
(bind <fld3> (compound <fld3> <v3>)))
(bind <instance>
(make objclass ^fld1 <fld1> ^fld2 <fld2> ^fld3 <fld3>))
\end{verbatim}
\end{exampl}
\subsection{Using Views to Fetch Data}
Using SQL views to fetch data from one or more tables into a specified
class of object is perfectly acceptable and easily done. However, if
you are using multiple tables, you can use views only to read database
records, not to insert or update database records in multiple
tables. (You cannot use views that contain aggregates to write data
either; see the \emph{DEC Rdb Guide to SQL Programming} section on
\co{CREATE VIEW} for restrictions.)
You can define a view to achieve the one-to-one mapping of object
class to database table names, or of object attributes to database
field names, required by the simple forms of the fetch, insert, and
update actions. For example:
\begin{exampl}[Using Views to Fetch Data]
\begin{verbatim}
CREATE TABLE Y (X INTEGER, Z CHAR(20), ...);
CREATE VIEW A (B, C) AS SELECT X, Z FROM Y;
\end{verbatim}
\vspace{1ex}
In this example, attribute \verb|^B| of object class \co{A} maps to
field \co{B} in view \co{A} (satisfying the 1-to-1 name mapping
requirement), while the view's field \co{B} in turn corresponds to
field \co{X} in the underlying table \co{Y} to which the view
provides access.
\end{exampl}
\section{Using Database Key Values}
You can fetch database key values and use them inside RuleWorks, but
you cannot use them to insert or update records. The SQL interface
translates database key values into character strings, such as 1:2:3,
for the database area, page, and line numbers of the fetched records.
You can declare an attribute called \verb|^DBKEY| and test whether it
is \co{NIL} to find out if the object was fetched from the database or
not.
You can compare two fetched database key values for equality.
\begin{quote}
\textbf{Note:} Database key values are not persistent. They are
valid for only the duration of a single attachment to the database
(or less if you use the default transaction scope).
\end{quote}
\section{Writing to a Database}
You can write WMO attribute values to a database in one of two ways:
by updating existing database records or by inserting new ones. You
can also choose either the simple or the flexible form of the update
and insert actions. This section describes the following RHS actions:
\begin{itemize}
\item \co{SQL-UPDATE}
\item \co{SQL-UPDATE-FROM-OBJECT}
\item \co{SQL-INSERT}
\item \co{SQL-INSERT-FROM-OBJECT}
\end{itemize}
Remember that you must explicitly start all write transactions with an
\co{SQL-START} action.
\subsection{Updating Existing Records}
Updating existing records modifies data fields without creating any
new database records. The \co{SQL-UPDATE-FROM-OBJECT} action uses the
contents of an object to modify existing database records; the
\co{SQL-UPDATE} action uses constants or bound variables.
Both update actions allow you to use the SQL syntax for \co{WHERE} clauses
to specify which database records are modified. The syntax for the
\co{SQL-UPDATE-FROM-OBJECT} action is shown below:
\begin{quote}
\co{SQL-UPDATE-FROM-OBJECT}
\verb|<$|\it{id-variable}\verb|>| [\it{where-clause}]
\end{quote}
\co{SQL-UPDATE-FROM-OBJECT} modifies records in the database table
whose name matches the \co{OBJECT-CLASS} of the WMO specified by the
\co\$\it{id-variable} argument. This argument also specifies which
object provides the new data values for the update. If the object has
attributes that do not correspond to fields in the target database
table, those attributes are ignored. On the other hand, if the
database table has fields that do not correspond to attributes in the
object, those fields are not modified.
For example:
\begin{quote}
\begin{verbatim}
(sql-update-from-object <w> where fld1 = <var>)
\end{verbatim}
\end{quote}
Note that all of the fields in the database record(s) may be modified,
not just \co{fld1}. \co{SQL-UPDATE-FROM-OBJECT} uses all the
attribute values for the specified RuleWorks object to modify all the
corresponding data fields in the selected database records. Depending
on the \co{WHERE} clause, one or more records may be updated by a
single \co{SQL-UPDATE-FROM-OBJECT} action.
The \co{SQL-UPDATE} action uses the SQL syntax for \co{SET} clauses to
specify which database fields are modified. The syntax for the
\co{SQL-UPDATE} action is shown below:
\begin{quote}
\co{SQL-UPDATE} \it{table-name} \it{SET-clause} [\it{where-clause}]
\end{quote}
The table-name argument can be a symbol or bound variable; the
\it{SET-clause} argument can contain constants or bound variables. As with
\co{SQL-UPDATE-FROM-OBJECT}, the \it{where-clause} argument is optional. For
example:
\begin{quote}
\begin{verbatim}
(sql-update tbl set fld1 = 0 where fld2 > 10)
\end{verbatim}
\end{quote}
Note that one or many database records may be updated by a single
RuleWorks \co{SQL-UPDATE} execution. If you want to update only one record
per firing of this rule, you must write a \co{WHERE} clause that restricts
the selection to a single record.
\subsection{Inserting New Records}
The \co{SQL-INSERT-FROM-OBJECT} action adds to the database a single
new record whose field values are the attribute values of a specified
object. The \co{SQL-INSERT} action adds one or more new records to the
database. \co{SQL-INSERT-FROM-OBJECT} does not remove the object whose
data it stores in the database.
The syntax of the \co{SQL-INSERT-FROM-OBJECT} action is shown below:
\begin{quote}
\co{SQL-INSERT-FROM-OBJECT} \verb|<$|\it{id-variable}\verb|>|
\end{quote}
For example:
\begin{quote}
\begin{verbatim}
(sql-insert-from-object <w>)
\end{verbatim}
\end{quote}
The syntax of the \co{SQL-INSERT} action is shown below:
\begin{quote}
\co{SQL-INSERT} \it{table-name} \it{SQL-expr}
\end{quote}
The \it{SQL-expr} argument lists the field names into which values are
to be inserted and the new values themselves. For example:
\begin{quote}
\begin{verbatim}
(sql-insert tbl |(| fld1, fld2 |) values (| 10, 'abc' |)|)
\end{verbatim}
\end{quote}
\section{Error Handling}
The SQL interface signals error conditions by creating WMOs whose
class name is
\verb|SQL$MSG|. In order to accept these objects, your RuleWorks
program must include the following \co{OBJECT-CLASS} declaration:
\begin{exampl}[\co{OBJECT-CLASS} Declaration]
\begin{verbatim}
(object-class sql$msg
^sev ; severity code
^cond ; condition code, or message name
^text ; description of the error
^rule) ; the name of the rule that executed the SQL action
\end{verbatim}
\end{exampl}
The following example, SQL Error Objects, shows a few sample objects
of class \verb|SQL$MSG|.
\begin{exampl}[SQL Error Objects]
\begin{Verbatim}[commandchars=\\\{\}]
\RWP\cmd{ppwm sql$msg}
#54 60 [ATTACH-DATABASE:DO-IT]
(SQL$MSG ^SEV W ^COND SQLATTFAI
^TEXT SQL attach to database failed
^RULE ATTACH-DATABASE:DO-IT)
#56 62 [FETCH-ITEMS-FROM-DATABASE:HARDWARE-OPTION]
(SQL$MSG ^SEV W ^COND SQLFETPRE
^TEXT Preparation of SQL fetch statement failed
^RULE FETCH-ITEMS-FROM-DATABASE:HARDWARE-OPTION)
#60 66 [FETCH-ITEMS-FROM-DATABASE:HARDWARE-OPTION]
(SQL$MSG ^SEV W ^COND SQLFETPRE
^TEXT Preparation of SQL fetch statement failed
^RULE FETCH-ITEMS-FROM-DATABASE:HARDWARE-OPTION)
\end{Verbatim}
\end{exampl}
You can write rules to process
\verb|SQL$MSG| objects as they are produced; you decide how, or
whether, to proceed after an SQL warning. The following example,
Handling an SQL Error, shows a rule that halts the program when the
attachment to the database fails.
\begin{exampl}[Handling an SQL Error]
\begin{verbatim}
(rule abort-on-db-attach-failure
(sql$msg ^cond sqlattfai ^text <text> ^rule )
-->
(write (crlf) |Execution of| |caused the following error:|)
(write (crlf) <text>)
(halt))
\end{verbatim}
\end{exampl}
\section{Ending an SQL Transaction}
When you end an SQL transaction, you can either apply (commit) any
changes to the database made during the transaction, or you can undo
them (rollback). Use the \co{SQL-COMMIT} action to apply the changes, the
\co{SQL-ROLLBACK} action to undo them. Both of these actions complete the
current SQL transaction. Their syntax is shown below:
\begin{quote}
\co{SQL-COMMIT}
\co{SQL-ROLLBACK}
\end{quote}
The SQL interface automatically performs an \co{SQL-COMMIT} action to
terminate any transaction you started implicitly by a fetch operation.