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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This document was generated using DocBuilder 3.3.3 -->
<HTML>
<HEAD>
<TITLE>Database Queries
</TITLE>
<SCRIPT type="text/javascript" src="../../../../doc/erlresolvelinks.js">
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#FF00FF"
ALINK="#FF0000">
<CENTER>
<A HREF="http://www.erlang.se"><IMG BORDER=0 ALT="[Ericsson AB]" SRC="min_head.gif"></A>
</CENTER>
<A NAME="2"><!-- Empty --></A>
<H2>2 Database Queries
</H2>
<P>This chapter describes Mnemosyne, the Mnesia database query
language, and the syntax, semantics, and rules which apply to
Mnesia queries. The following sections are included:
<P>
<UL>
<LI>
Mnemosyne - the Mnesia query language
</LI>
<LI>
Evaluating queries
</LI>
<LI>
Mnesia query examples
</LI>
<LI>
Matching
</LI>
<LI>
Generated functions
</LI>
</UL>
<P>The following notational conventions are used in this chapter:
<P>
<UL>
<LI>
Reserved words and symbols are written like this: <CODE>table</CODE>.
</LI>
<LI>
Syntactic categories are written like this: <CODE><pattern></CODE>.
</LI>
</UL>
<A NAME="db_queries"><!-- Empty --></A><A NAME="2.1"><!-- Empty --></A>
<H3>2.1 Mnemosyne - the Mnesia Query Language</H3>
<P><STRONG>Mnemosyne</STRONG> is the query language and the optimizing query
compiler for the Mnesia Database Management System.
<A NAME="2.1.1"><!-- Empty --></A>
<H4>2.1.1 General Information about Queries</H4>
<P>Database <STRONG>queries</STRONG> are used when more complex
operations than just a simple key-value lookup are required on
a database. A query can find all records in a table that fulfills
a given property. For example, think of a table storing the
status of subscriber lines in a telephone exchange. A query in
such a table can take the format: "Which subscriber
<STRONG>lines</STRONG> are 'blocked'?".
<P>A query can also find records on the basis of their relationship to
other records in the same table, or in other tables. If the
table, which stores subscriber lines, is accompanied by a table,
which pairs subscriber numbers with a subscriber line
identification, we can modify our previous query and ask:
"Which subscriber <STRONG>numbers</STRONG> are 'blocked' ?". This can
be answered by constructing a query, which finds the blocked
subscriber line identifications in the subscriber line table,
and then finds the associated subscriber number in the table,
which pairs subscriber number and subscriber line
identifications.
<P>However, the proposed solution may not be the most efficient
solution, because it depends on what
the tables look like in runtime. In other words, how many records the
table contains, and the number of different values stored.
<P>In a situation where there are only a couple of subscriber
numbers but a million blocked lines, it would be far more
efficient to first find the subscribers and then check if
their line is blocked. The query evaluation order depends on
how large the tables are compared to each other. The
evaluation order also depends on key and other value
distribution, and if there are any indices defined (refer to
<STRONG>Mnesia Chapter 5: Indexing</STRONG> for more information).
<P>The query compiler resolves the evaluation order. We need only
express <STRONG>what</STRONG> we want to do, and the query compiler
and query evaluator will determine the best evaluation order.
Therefore, we can express the query in the most readable
form.
<A NAME="2.1.2"><!-- Empty --></A>
<H4>2.1.2 Queries in Mnesia</H4>
<P>Queries in Mnemosyne use first order predicate logic (similar
to Prolog),
but in an syntax suitable for Erlang. The "query list
comprehension" used in Mnemosyne is taken from the functional
languages community. The advantage over embedded SQL, is that
the constructs integrate smoothly with the Erlang language.
<A NAME="sub_query"><!-- Empty --></A>
<P>To illustrate the Mnemosyne query language, we will show the Erlang
code for the subscriber line and subscriber number tables
discussed above. We define two tables <CODE>subscriber</CODE> and
<CODE>line</CODE>. Their corresponding record declarations in the
file <CODE>subscriber.hrl</CODE> are:
<PRE>
-record(subscriber, {snb,
cost_limit,
li}).
</PRE>
<PRE>
-record(line, {li,
state}).
</PRE>
<P>The query "which subscriber numbers are blocked?" can also be
expressed as "which subscribers have lines which are in state 'blocked'".
This query can be coded as follows:
<PRE>
query
[ S.snb || % collect the subscriber number
S <- table(subscriber), % where S is taken from the subscriber table
L <- table(line), % and L is taken from the line table
L.state = blocked, % and the state of that line is blocked
L.li = S.li % and L and S uses the same li
]
end
</PRE>
<P>In the example above, the aim is to get an answer from a logical
relation. Consider also the following example:
<PRE>
query [E.name || E <- table(employee),
E.sex = female]
end
</PRE>
<P>This means "the Erlang list of all female employees". A formulation
closer to the list comprehension is: "the Erlang list of all
names of E such that E is in the table
<CODE>employee</CODE> and E's sex is female".
<P>Some words have a direct correspondence to the elements in the list
comprehension notation:
<P>
<CENTER>
<TABLE CELLSPACING=0 CELLPADDING=2 BORDER=1>
<CAPTION ALIGN=BOTTOM><EM>Natural Language Translation</EM></CAPTION>
<TR>
<TD ALIGN="LEFT" VALIGN="MIDDLE">
the Erlang list of all
</TD>
<TD ALIGN="LEFT" VALIGN="MIDDLE">
<CODE>[ ]</CODE>
</TD>
</TR>
<TR>
<TD ALIGN="LEFT" VALIGN="MIDDLE">
such that
</TD>
<TD ALIGN="LEFT" VALIGN="MIDDLE">
<CODE>||</CODE>
</TD>
</TR>
<TR>
<TD ALIGN="LEFT" VALIGN="MIDDLE">
is in
</TD>
<TD ALIGN="LEFT" VALIGN="MIDDLE">
<CODE><-</CODE>
</TD>
</TR>
<TR>
<TD ALIGN="LEFT" VALIGN="MIDDLE">
and
</TD>
<TD ALIGN="LEFT" VALIGN="MIDDLE">
<CODE>,</CODE>
</TD>
</TR>
</TABLE>
</CENTER>
<P>Another query component is <STRONG>rules</STRONG>, which can be compared to
<STRONG>views</STRONG> in Relational Databases, where the purpose is
to define a "virtual table". This "table" looks like an
ordinary table to the user, which means that queries can be
formulated on stored data (as well as views). In the subscriber
line example, a rule can give the subscriber number and the
corresponding line status from both tables, and there is no
need to create a third table.
<P>The rule is a definition of how
to calculate the records on demand from a query. In Erlang
modules, rules are written with the same syntax as the bodies
in the query list comprehensions. They are exported and can be
used by other modules.
<P>Our <CODE>subscriber</CODE> example formulated as a rule would look as
follows:
<A NAME="mnemosyne_rule_example"><!-- Empty --></A>
<PRE>
blocked_subscribers(S, subscriber) :-
S <- table(subscriber),
L <- table(line),
L.state = blocked,
L.li = S.li.
</PRE>
<P>This rule can be used in a query in the same manner as a table
but with the keyword <CODE>rule</CODE> substituted for <CODE>table</CODE>.
<PRE>
query [ S.snb || S <- rule(blocked_subscribers) ] end
</PRE>
<A NAME="2.1.3"><!-- Empty --></A>
<H4>2.1.3 Query Syntax</H4>
<P> Database queries can be included in an Erlang program, but there
must be a directive in the Erlang file which informs the compiler
about its behavior towards queries. This directive is:
<PRE>
-include_lib("mnemosyne/include/mnemosyne.hrl").
</PRE>
<P>The high-level syntax of the query list comprehension is:
<PRE>
query [ <pattern> || <body> ] end
</PRE>
<A NAME="lc_body_syntax"><!-- Empty --></A>
<P>The <CODE><body></CODE> is a comma-separated sequence of:
<P>
<OL>
<LI>
<CODE><logical-variable> <- table( <table-name> [ , <table-type> ] )</CODE>
</LI>
<LI>
<CODE><logical-variable> <- rule( <rule-name> )</CODE>
</LI>
<LI>
<CODE><logical-variable> <- rule( <rule-name> )</CODE>
</LI>
<LI>
<CODE><logical-variable> <- rule( <module> : <rule-name> ])</CODE>
</LI>
<LI>
<CODE><logical-variable> <- <erlang-list-expression></CODE>
</LI>
<LI>
<CODE><expression> <relop> <expression></CODE>
</LI>
<LI>
<CODE><erlang-test-expression></CODE>
</LI>
</OL>
<P>The <CODE><relop></CODE> operators are:
<P>
<UL>
<LI>
<CODE>=</CODE> for unification
</LI>
<LI>
<CODE>/=</CODE> for not unification
</LI>
<LI>
<CODE><</CODE> for less than
</LI>
<LI>
<CODE>></CODE> for greater than
</LI>
<LI>
<CODE>=<</CODE> for equal to or less than
</LI>
<LI>
<CODE>>=</CODE> for equal to or greater than.
</LI>
</UL>
<P>A <CODE><logical-variable></CODE> is written exactly as an Erlang
variable. The <CODE><table-name></CODE>, <CODE><table-type></CODE>,
<CODE><rule-name></CODE> and
<CODE><module></CODE> are atoms. The <CODE><table-name></CODE> and
<CODE><table-type></CODE> can also be
an Erlang variable. The logical variables are local to a list
comprehension and shadows any Erlang variable with the same
name.
<P>The <CODE><pattern></CODE> is an Erlang term without function calls. It
may contain (bound) Erlang variables and it usually has one or
more <CODE><logical-variable></CODE>, since these are used to get
data out from the query body and into the produced list.
<P>An <CODE><expression></CODE> is any Erlang expression which may include
function calls and <CODE><logical-variable></CODE>. The variant
<CODE><erlang-list-expression></CODE> is an
<CODE><expression></CODE> which must produce a list where all elements are
records of the same type.
<P> The <CODE><erlang-test-expression></CODE> is an <CODE><expression></CODE>
which has the values <CODE>true</CODE> or <CODE>false</CODE>.
<P>Erlang variables are allowed in all variations of <CODE><expression></CODE>
and in <CODE><pattern></CODE>. They must be bound in the query list
comprehension.
<A NAME="2.1.4"><!-- Empty --></A>
<H4>2.1.4 Query Semantics</H4>
<P>The constructs used in the Mnemosyne query language have the following meanings:
<P>
<UL>
<LI>
<STRONG>Comma</STRONG>. The comma, used to separate different body
elements, is equivalent to "and". Thus, the body
can be viewed as a collection of tests and statements which
should be true for each solution which is produced when
evaluating the query list comprehension. Refer to <A HREF="#sub_query"> subscriber query</A> as an example of
this.
</LI>
<LI>
<STRONG><CODE><logical-variable> <- ...</CODE></STRONG>. This expression means
that the variable is taken from the values in the expression
to the right of the arrow. For example, <CODE>E <- [#e{a=1},
#e{a=2}]</CODE> says that <CODE>E</CODE> takes the values
<CODE>#e{a=1}</CODE>, or <CODE>#e{a=2}</CODE>
</LI>
<LI>
<STRONG><CODE><-</CODE></STRONG>. These constructs usually generate
values. However, if the logical variable is bound it tests
that value. If a test fails it means that the query tries
another alternative. For example:
<PRE>
query [ X.a || X <- [#e{a=1}, #e{a=2}],
X <- [#e{a=3}],
.... ]
end
</PRE>
The body means that the field 'a' of <CODE>X</CODE> should be 3 and at
the same time either 1 or 2. So the list of solutions will
always be empty. <BR>
</LI>
</UL>
<P>The test <CODE><expression> <relop> <expression></CODE> and the
<CODE>true</CODE>-or-<CODE>false</CODE> returning test
<CODE><erlang-test-expression></CODE> simply filters out the solutions. The
purpose of the latter test is to provide user defined data tests.
<P>We will next consider the logical variables <STRONG>associated
records</STRONG> in an expression like <CODE>x <- table(a)</CODE>. We
have already established the following rules and assumptions:
<P>
<OL>
<LI>
the values stored in tables are records
</LI>
<LI>
all records in a table must be of the same type
</LI>
<LI>
by default, the record definition has the same name as the table itself
</LI>
<LI>
The <CODE><logical-variable></CODE> must have the same record association as the records produced by the right side of the <CODE><-</CODE> constructs.
</LI>
</OL>
<P>In the example <CODE>X <- table(a)</CODE>, the associated record of
<STRONG>x</STRONG> is <STRONG>a</STRONG> because table <STRONG>a</STRONG> stores
records with the name <STRONG>a</STRONG>. Since release 3.4 of Mnesia it has
been possible to separate record name and its table type.
If the type of the table is different from its name, this can
be specified in Mnemosyne using <CODE>X <- table(Name, Type)</CODE>
where Name is the Name of the table and Type is the record name.
<P>Similar to tables, rules produce or test records. The return type
for a rule is by default the name of the rule. Rules can be declared
to return other types.
This makes it possible to construct a rule for some
special cases with a name like <CODE>blocked_subscriber</CODE> which
still produces or tests subscriber records.
<P>In Erlang we must always tell the compiler which record definition
it should use by putting the record name after a hash mark. In
general, this is not needed in Mnemosyne since, in most cases,
the query
compiler can deduce the associated record. That
is the reason <CODE>S.li</CODE> is acceptable instead of the
full <CODE>S#subscriber.li</CODE>. It will not cause an error
if the longer version
was written, but if we do write the record name it must be the
same record name as the one the query compiler deduces. Sometimes
the compiler is unable to find the
associated record. When this happens, an error message is
issued.
It is also preferred to write out the type of the associated record
for performance reasons. If the associated record is part of a complex
constraint, the constraint may be compiled to a function if the
type of the associated record is known (explicitly or
deducable) at Erlang compile time.
<P>
<TABLE CELLPADDING=4>
<TR>
<TD VALIGN=TOP><IMG ALT="Note!" SRC="note.gif"></TD>
<TD>
<P> A function used in a query list comprehension must <STRONG>never</STRONG>
directly or indirectly:
<P>
<OL>
<LI>
have side effects;
</LI>
<LI>
access the database neither by a query nor by Mnesia functions;
</LI>
<LI>
spawn processes, or;
</LI>
<LI>
send or receive messages.
</LI>
</OL>
</TD>
</TR>
</TABLE>
<A NAME="2.1.5"><!-- Empty --></A>
<H4>2.1.5 Rules</H4>
<P>A rule is composed of <STRONG>clauses</STRONG> and each clause has the structure:
<PRE>
<head> :- <body>
</PRE>
<P>
<UL>
<LI>
The clauses are separated by semicolon, and the rule is terminated by a dot.
</LI>
<LI>
The <CODE><head></CODE> looks like an Erlang function with one or two arguments,
where the first argument is a variable and the second, optional, argument
an atom. If there is a second argument, it must be present in all clauses and
have the same value.
</LI>
<LI>
The <CODE><body></CODE> has the same syntax as the <CODE><body></CODE>. <A HREF="#lc_body_syntax">in query list comprehensions</A>
</LI>
<LI>
The argument variable of a rule clause has an associated record.
</LI>
<LI>
The default associated record is the name of the rule. This can be
changed by declaring the associated record type in the head of the clause:
<PRE>
<rule-name> (<return-var>, <record-name>)
</PRE>
The syntax used in previous mnemosyne versions, by declaring the the
associated recordtype with an <CODE>argtype</CODE> declaration still works but
is depreciated.
</LI>
</UL>
<P>
<TABLE CELLPADDING=4>
<TR>
<TD VALIGN=TOP><IMG ALT="Note!" SRC="note.gif"></TD>
<TD>
<P> The <CODE><logical-variable></CODE> mentioned in the <CODE><head></CODE> must also occur in the <CODE><body></CODE>. </TD>
</TR>
</TABLE>
<P>Review the <A HREF="#mnemosyne_rule_example"> rule example</A>.
<PRE>
blocked_subscribers(S, subscriber) :-
S <- table(subscriber),
L <- table(line),
L.state = blocked,
L.li = S.li.
</PRE>
<P>It produces a list of <CODE>subscriber</CODE> records.
Rules with a single argument return records of the same
type as the name of the rule. For example, the following
rule produces records of type <CODE>blocked</CODE>
<PRE>
-record (blocked, {snb, li}).
blocked (X) :-
S <- table (subscriber),
L <- table(line),
L.state = blocked,
L.li = S.li,
X = #blocked{snb=S#subscriber.snb, li=S#subscriber.li}.
</PRE>
<A NAME="2.2"><!-- Empty --></A>
<H3>2.2 Evaluating Queries</H3>
<P>The previous sections described how to define queries. This
section describes how to evaluate queries.
<P>The principle is simple: query list comprehensions, compile and
optimize the query and return a <STRONG>handle</STRONG>. This handle is
then passed on for execution:
<PRE>
Handle =
query
[ S.snb || S <- table(subscriber),
S.li = none]
end,
AllAnswers =
mnesia:transaction(
fun() ->
mnemosyne:eval(Handle)
end)
</PRE>
<P>There are three ways of evaluating queries. The <CODE>mnemosyne:eval/1</CODE>
is the simplest of the three. It takes a handle and returns all
solutions. Sometimes we only need to view a few solutions,
examine them and possibly get more. Think of an airline routing
database: you do not want to know all possible connections
between two cities, but usually enough information is given
after observing one or two.
<P>Use the <STRONG>cursor</STRONG> with a query evaluation to produce a few
solutions only. With a handle we create a cursor by calling
<CODE>mnemosyne:cursor/1</CODE>. With the cursor we can repeatedly
call <CODE>mnemosyne:next_answers</CODE> to get more solutions. When
an empty list is returned there are no more possible solutions.
Delete the cursor with <CODE>mnemosyne:delete_cursor/1</CODE>.
<PRE>
Handle =
query
[ S.snb || S <- table(subscriber),
S.li = none]
end,
AFewAnswers =
mnesia:transaction(
fun() ->
Cursor = mnemosyne:cursor(Handle),
% now get at least two but not
% more than five solutions:
L = mnemosyne:next_answers(Cursor,2,5),
mnemosyne:delete_cursor(Cursor),
L
end)
</PRE>
<P>A query evaluation can be time consuming, but can be broken up by using the cursor with <CODE>setup_query/1</CODE> and <CODE>init_query/1</CODE>:
<PRE>
Handle =
query
[ S.snb || S <- table(subscriber),
S.li = none]
end,
QuerySetup = mnemosyne:setup_query(Handle),
AFewAnswers =
mnesia:transaction(
fun() ->
Cursor = mnemosyne:init_query(QuerySetup),
mnemosyne:next_answers(Cursor, 5, 5)
end),
% Here we may call more init_query-next_answers constructions
% with the same Handle. Note that the query is evaluated from
% "scratch" because of the call to mnemosyne:init_query/1.
mnemosyne:delete_query(QuerySetup)
</PRE>
<P>Because of table updates, a query which is compiled and optimized
may be incorrect when the handle returns. This can be rectified with
the function <CODE>mnemosyne:reoptimize/1</CODE> which takes a handle,
re-optimizes the query and returns a new handle.
<A NAME="2.3"><!-- Empty --></A>
<H3>2.3 Query Examples</H3>
<P>This section describes an example which illustrates the use of Mnemosyne.
The example given is of a simplified local
exchange, with AXE-10 exchange as a model. The purpose of this
section is to show different constructs in a telecom
environment. It should not be taken as a proposed data model for
a modern telecom system.
<P>Our telephone example includes the following components,
relationships, and events:
<P>
<UL>
<LI>
The exchange has a number of <STRONG>subscribers</STRONG>.
</LI>
<LI>
Each subscriber has a <STRONG>subscriber number</STRONG>, which is abbreviated
<STRONG>snb</STRONG>.
</LI>
<LI>
Each physical line enters the exchange through a <STRONG>line interface
card</STRONG>. Lines are abbreviated <STRONG>li</STRONG>.
</LI>
<LI>
The <STRONG>li</STRONG> has an associated <STRONG>status</STRONG> which indicates if the line is blocked, or available.
</LI>
<LI>
One single table stores the accumulated cost for each subscriber.
</LI>
</UL>
<A NAME="2.3.1"><!-- Empty --></A>
<H4>2.3.1 Program Definitions</H4>
<P>We identify three tables:
<P>
<UL>
<LI>
<CODE>subscriber</CODE> with subscriber numbers <CODE>snb</CODE>, line interface number <CODE>li</CODE>, and a maximum cost <CODE>cost_limit</CODE> which must not be exceeded.
</LI>
<LI>
<CODE>line</CODE> with line interface number <CODE>li</CODE>, and its <CODE>state</CODE>.
</LI>
<LI>
<CODE>account</CODE>, a table which stores the cost of calls. It has an <CODE>snb</CODE> field, and the accumulated cost in <CODE>cost</CODE>.
</LI>
</UL>
<P>The corresponding record definitions are stored in a file named <CODE>subscriber.hrl</CODE>, which has the following record definitions:
<PRE>
-record(subscriber, {snb,
cost_limit,
li}).
</PRE>
<PRE>
-record(line, {li,
state}).
</PRE>
<PRE>
-record(account, {snb,
cost}).
</PRE>
<P>The program file is titled <CODE>subscriber.erl</CODE>. It declares the module name <CODE>subscriber</CODE>, calls the record definition in <CODE>subscriber.hrl</CODE>, and Mnesia query support <CODE>mnemosyne.hrl</CODE>.
<PRE>
-module(subscriber).
-compile(export_all).
-include("subscriber.hrl").
-include_lib("mnemosyne/include/mnemosyne.hrl").
</PRE>
<P>We then create the required tables and load data by entering table definitions into a file named <CODE>subscriber.tables</CODE>, which has the following content:
<PRE>
{tables,
[{subscriber, [{attributes, [snb,cost_limit,li]}]},
{line, [{attributes, [li, state]}]},
{account, [{attributes, [snb, cost]}]}
]
}.
%% Subscribers
{subscriber, 1230, 0, none}.
{subscriber, 1231, 0, none}.
{subscriber, 1232, 0, none}.
{subscriber, 1233, 0, none}.
{subscriber, 1234, 100, {li,1}}.
{subscriber, 1235, 200, {li,3}}.
{subscriber, 1236, 150, {li,2}}.
{subscriber, 1237, 0, none}.
{subscriber, 1238, 0, none}.
{subscriber, 1239, 0, none}.
%% Lines
{line, {li,0}, blocked}.
{line, {li,1}, normal}.
{line, {li,2}, normal}.
{line, {li,3}, blocked}.
{line, {li,4}, blocked}.
{line, {li,5}, blocked}.
{line, {li,6}, blocked}.
{line, {li,7}, blocked}.
%% Accounts
{account, 1234, 0}.
{account, 1235, 0}.
{account, 1236, 0}.
{account, 1237, 0}.
</PRE>
<A NAME="2.3.2"><!-- Empty --></A>
<H4>2.3.2 Program Output</H4>
<P>In our program, this file is called with the statement:
<PRE>
mnesia:load_textfile("subscriber.tables")
</PRE>
<P>To retrieve a list of all free subscriber numbers we call the following
function in a transaction:
<PRE>
free_subscriber_numbers() ->
mnemosyne:eval(
query [ S.snb || S <- table(subscriber),
S.li = none]
end
).
</PRE>
<P>The rule <CODE>too_high_cost/0</CODE> locates and returns all subscribers with an
accumulated cost that exceeds their limit:
<PRE>
limit_exceeded(S, subscriber) :-
S <- table(subscriber),
A <- table(account),
A.snb = S.snb,
A.cost > S.cost_limit.
</PRE>
<P>We could find all subscriber numbers of subscribers who have exceeded their cost limit as follows:
<PRE>
Q = query
[ S.snb || S <- rule(limit_exceeded) ]
end
</PRE>
<A NAME="2.4"><!-- Empty --></A>
<H3>2.4 Matching </H3>
<P>Mnesia provides the programmer with a method of matching objects
against a pattern. This is the Mnesia matching function:
<P><CODE>mnesia:match_object(Pattern) ->transaction abort | ObjList</CODE>.
<P>This function matches <CODE>Pattern</CODE> for objects. A <CODE>Pattern</CODE>
is a tuple with the name (identity) of the table as the first element.
The table collates all data retrieved.
<P>In comparison to a list comprehension query, <CODE>mnesia:match_object</CODE> is a low level
function. The following two functions both return the same
objects; however, the second example uses matching.
<PRE>
f1() ->
Q = query
[E || E <- table(employee),
E.sex = female]
end,
F = fun() -> mnemosyne:eval(Q) end,
mnesia:transaction(F).
</PRE>
<P>and
<PRE>
f2() ->
WildPat = mnesia:table_info(employee, wild_pattern),
Pat = WildPat#employee{sex = female},
F = fun() -> mnesia:match_object(Pat) end,
mnesia:transaction(F).
</PRE>
<P>The pattern supplied to the <CODE>mnesia:match_object/1</CODE>
function must be a valid record, and the first element
of the provided tuple must be a valid table name. The
special element <CODE>'_'</CODE> matches all the records.
<P>There are advantages in using the Mnemosyne query syntax
instead of the <CODE>mnesia:match_object/1</CODE> function:
<P>
<UL>
<LI>
The pattern is computed in compile time by the
Mnemosyne compiler instead of doing it in run time in the
<CODE>f2/0</CODE> function.
<BR>
</LI>
<LI>
Mnemosyne provides more sophisticated evaluation
optimizations based on indices and on statistics from and about the
table.
<BR>
Whereas, the optimizations that <CODE>mnesia:match_object/1</CODE>
function provides are limited in both scope and number.
The <CODE>mnesia:match_object</CODE> function is also performed
during run time, which in turn reduces performance.
<BR>
</LI>
<LI>
The Mnemosyne query syntax is quite compact and makes
it easier to express complex queries.
<BR>
</LI>
</UL>
<P>It is also possible to use the match function if we want to
check the equality of different attributes. Assume we have
the following record definition:
<PRE>
-record(foo, {a, b, c}).
</PRE>
<P>The pattern <CODE>{foo, '$1', '$1', '_'}</CODE> then extracts all objects of type
<CODE>foo</CODE> where the first two attributes have the same value.
<P>If the key attribute is bound in a pattern, the match operation is very efficient.
The pattern <CODE>{foo, 123, '_', elvis}</CODE> can be used to extract all
objects with key <CODE>123</CODE>, and the last attribute set to the atom
<CODE>elvis</CODE>. This is the same as extracting all the <CODE>elvis</CODE>
objects from the result of <CODE>mnesia:read({foo, 123})</CODE>, but
more efficient.
<P>If the key attribute in a pattern is given as <CODE>'_'</CODE>, or <CODE>'$1'</CODE>, the
whole <CODE>foo</CODE> table must be searched for objects that match. If the table
is large, this may be a time consuming operation. This can be remedied with
indices (refer to <STRONG>Mnesia Chapter 5: Indexing</STRONG> for more information).
<P>This chapter closes with an example of information extraction from a Company database:
<P>
<UL>
<LI>
all employees who have a salary higher than <CODE>X</CODE>.
</LI>
<LI>
all employees who work in the <CODE>Dep</CODE> department.
</LI>
</UL>
<P>The first example demonstrates the query execution with
list comprehension notation. The second example illustrates a
query coded with a matching function.
<P>The list comprehension based implementation looks as follows:
<PRE>
get_emps(Salary, Dep) ->
Q = query
[E || E <- table(employee),
At <- table(at_dep),
E.salary > Salary,
E.emp_no = At.emp,
At.dept_id = Dep]
end,
F = fun() -> mnemosyne:eval(Q) end,
mnesia:transaction(F).
</PRE>
<P>The data model for the Company database introduced in
the Mnesia documentation was designed to facilitate the posting of
queries like the one shown above.
<P>To implement the same query by directly searching the database is
more complex. The following function does precisely this:
<PRE>
get_emps2(Salary, Dep) ->
Epat = mnesia:table_info(employee, wild_pattern),
Apat = mnesia:table_info(at_dep, wild_pattern),
F = fun() ->
All = mnesia:match_object(Epat),
High = filter(All, Salary),
Alldeps = mnesia:match_object(Apat),
filter_deps(High, Alldeps, Dep)
end,
mnesia:transaction(F).
filter([E|Tail], Salary) ->
if
E#employee.salary > Salary ->
[E | filter(Tail, Salary)];
true ->
filter(Tail, Salary)
end;
filter([], _) ->
[].
filter_deps([E|Tail], Deps, Dep) ->
case search_deps(E#employee.name, Deps, Dep) of
true ->
[E | filter_deps(Tail, Deps, Dep)];
false ->
filter_deps(Tail, Deps, Dep)
end;
filter_deps([], _,_) ->
[].
search_deps(Name, [D|Tail], Dep) ->
if
D#at_dep.emp == Name,
D#at_dep.dept_id == Dep -> true;
true -> search_deps(Name, Tail, Dep)
end;
search_deps(Name, Tail, Dep) ->
false.
</PRE>
<P>The function <CODE>mnesia:match_object/1</CODE> will automatically
make use of indices if any exist. However, no heuristics are
performed in order to select the best index, if
more than one exists.
<P>As can be seen, the list comprehension provides a more elegant solution.
<A NAME="2.5"><!-- Empty --></A>
<H3>2.5 Matching in Record Fields</H3>
<P>There is a difference when matching record fields in a
mnemosyne list comprehension and in Erlang in general
(for example, a function clause header). The following code
returns true for all <CODE>employee</CODE> where <CODE>emp_id</CODE> is <CODE>312</CODE>
or <CODE>400</CODE>:
<PRE>
test_employee(#employee{emp_id = 312}) -> true;
test_employee(#employee{emp_id = 400}) -> true;
test_employee(_) -> false.
</PRE>
<P> That is, it does not check other fields of the employee record.
Compare that with the following mnemosyne query:
<PRE>
query [E || E <- table(employee),
E <- [#employee{emp_id=312},
#employee{emp_id=400}]]
</PRE>
<P> The query will return all employees from the employee table
whos <CODE>emp_id</CODE> is either <CODE>312</CODE> or <CODE>400</CODE>
<STRONG> and have the other fields set to the default values
for an employee</STRONG>.
To select all items that have a field set to some values
(disregarding the other fields) the constraint can be put in
separate function. For example, select all employees whos <CODE>emp_id</CODE>
is either <CODE>312</CODE> or <CODE>400</CODE> independently of other fields:
<PRE>
query [E || E <- table(employee),
test_employee(E)]
test_employee(#employee{emp_id = 312}) -> true;
test_employee(#employee{emp_id = 400}) -> true;
test_employee(_) -> false.
</PRE>
<P> If there is only one acceptable value for a record field
it is more efficient to write it
directly in the query. Select employees whos <CODE>emp_id</CODE> is 312:
<PRE>
query [E || E <- table(employee),
E#employee.emp_id = 312]
</PRE>
<CENTER>
<HR>
<SMALL>
Copyright © 1991-2006
<A HREF="http://www.erlang.se">Ericsson AB</A><BR>
</SMALL>
</CENTER>
</BODY>
</HTML>
|