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 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>32.9.C-Language Functions</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
<link rev="made" href="pgsql-docs@postgresql.org">
<meta name="generator" content="DocBook XSL Stylesheets V1.70.0">
<link rel="start" href="index.html" title="PostgreSQL 8.1.4 Documentation">
<link rel="up" href="extend.html" title="Chapter32.Extending SQL">
<link rel="prev" href="xfunc-internal.html" title="32.8.Internal Functions">
<link rel="next" href="xaggr.html" title="32.10.User-Defined Aggregates">
<link rel="copyright" href="ln-legalnotice.html" title="Legal Notice">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="sect1" lang="en">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="xfunc-c"></a>32.9.C-Language Functions</h2></div></div></div>
<a name="id706106"></a><p> User-defined functions can be written in C (or a language that can
be made compatible with C, such as C++). Such functions are
compiled into dynamically loadable objects (also called shared
libraries) and are loaded by the server on demand. The dynamic
loading feature is what distinguishes “<span class="quote">C language</span>” functions
from “<span class="quote">internal</span>” functions [mdash ] the actual coding conventions
are essentially the same for both. (Hence, the standard internal
function library is a rich source of coding examples for user-defined
C functions.)
</p>
<p> Two different calling conventions are currently used for C functions.
The newer “<span class="quote">version 1</span>” calling convention is indicated by writing
a <code class="literal">PG_FUNCTION_INFO_V1()</code> macro call for the function,
as illustrated below. Lack of such a macro indicates an old-style
(“<span class="quote">version 0</span>”) function. The language name specified in <code class="command">CREATE FUNCTION</code>
is <code class="literal">C</code> in either case. Old-style functions are now deprecated
because of portability problems and lack of functionality, but they
are still supported for compatibility reasons.
</p>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="xfunc-c-dynload"></a>32.9.1.Dynamic Loading</h3></div></div></div>
<a name="id706185"></a><p> The first time a user-defined function in a particular
loadable object file is called in a session,
the dynamic loader loads that object file into memory so that the
function can be called. The <code class="command">CREATE FUNCTION</code>
for a user-defined C function must therefore specify two pieces of
information for the function: the name of the loadable
object file, and the C name (link symbol) of the specific function to call
within that object file. If the C name is not explicitly specified then
it is assumed to be the same as the SQL function name.
</p>
<p> The following algorithm is used to locate the shared object file
based on the name given in the <code class="command">CREATE FUNCTION</code>
command:
</p>
<div class="orderedlist"><ol type="1">
<li><p> If the name is an absolute path, the given file is loaded.
</p></li>
<li><p> If the name starts with the string <code class="literal">$libdir</code>,
that part is replaced by the <span class="productname">PostgreSQL</span> package
library directory
name, which is determined at build time.<a name="id706257"></a>
</p></li>
<li><p> If the name does not contain a directory part, the file is
searched for in the path specified by the configuration variable
<a href="runtime-config-client.html#guc-dynamic-library-path">dynamic_library_path</a>.<a name="id706280"></a>
</p></li>
<li><p> Otherwise (the file was not found in the path, or it contains a
non-absolute directory part), the dynamic loader will try to
take the name as given, which will most likely fail. (It is
unreliable to depend on the current working directory.)
</p></li>
</ol></div>
<p>
If this sequence does not work, the platform-specific shared
library file name extension (often <code class="filename">.so</code>) is
appended to the given name and this sequence is tried again. If
that fails as well, the load will fail.
</p>
<p> The user ID the <span class="productname">PostgreSQL</span> server runs
as must be able to traverse the path to the file you intend to
load. Making the file or a higher-level directory not readable
and/or not executable by the <span class="systemitem">postgres</span>
user is a common mistake.
</p>
<p> In any case, the file name that is given in the
<code class="command">CREATE FUNCTION</code> command is recorded literally
in the system catalogs, so if the file needs to be loaded again
the same procedure is applied.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p> <span class="productname">PostgreSQL</span> will not compile a C function
automatically. The object file must be compiled before it is referenced
in a <code class="command">CREATE
FUNCTION</code> command. See <a href="xfunc-c.html#dfunc" title="32.9.6.Compiling and Linking Dynamically-Loaded Functions">Section32.9.6, “Compiling and Linking Dynamically-Loaded Functions”</a> for additional
information.
</p>
</div>
<p> After it is used for the first time, a dynamically loaded object
file is retained in memory. Future calls in the same session to
the function(s) in that file will only incur the small overhead of
a symbol table lookup. If you need to force a reload of an object
file, for example after recompiling it, use the <a href="sql-load.html">LOAD</a> command or begin a
fresh session.
</p>
<p> It is recommended to locate shared libraries either relative to
<code class="literal">$libdir</code> or through the dynamic library path.
This simplifies version upgrades if the new installation is at a
different location. The actual directory that
<code class="literal">$libdir</code> stands for can be found out with the
command <code class="literal">pg_config --pkglibdir</code>.
</p>
<p> Before <span class="productname">PostgreSQL</span> release 7.2, only
exact absolute paths to object files could be specified in
<code class="command">CREATE FUNCTION</code>. This approach is now deprecated
since it makes the function definition unnecessarily unportable.
It's best to specify just the shared library name with no path nor
extension, and let the search mechanism provide that information
instead.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="xfunc-c-basetype"></a>32.9.2.Base Types in C-Language Functions</h3></div></div></div>
<a name="id706448"></a><p> To know how to write C-language functions, you need to know how
<span class="productname">PostgreSQL</span> internally represents base
data types and how they can be passed to and from functions.
Internally, <span class="productname">PostgreSQL</span> regards a base
type as a “<span class="quote">blob of memory</span>”. The user-defined
functions that you define over a type in turn define the way that
<span class="productname">PostgreSQL</span> can operate on it. That
is, <span class="productname">PostgreSQL</span> will only store and
retrieve the data from disk and use your user-defined functions
to input, process, and output the data.
</p>
<p> Base types can have one of three internal formats:
</p>
<div class="itemizedlist"><ul type="disc">
<li><p> pass by value, fixed-length
</p></li>
<li><p> pass by reference, fixed-length
</p></li>
<li><p> pass by reference, variable-length
</p></li>
</ul></div>
<p>
</p>
<p> By-value types can only be 1, 2, or 4 bytes in length
(also 8 bytes, if <code class="literal">sizeof(Datum)</code> is 8 on your machine).
You should be careful
to define your types such that they will be the same
size (in bytes) on all architectures. For example, the
<code class="literal">long</code> type is dangerous because it
is 4 bytes on some machines and 8 bytes on others, whereas
<code class="type">int</code> type is 4 bytes on most
Unix machines. A reasonable implementation of
the <code class="type">int4</code> type on Unix
machines might be:
</p>
<pre class="programlisting">/* 4-byte integer, passed by value */
typedef int int4;</pre>
<p>
</p>
<p> On the other hand, fixed-length types of any size may
be passed by-reference. For example, here is a sample
implementation of a <span class="productname">PostgreSQL</span> type:
</p>
<pre class="programlisting">/* 16-byte structure, passed by reference */
typedef struct
{
double x, y;
} Point;</pre>
<p>
Only pointers to such types can be used when passing
them in and out of <span class="productname">PostgreSQL</span> functions.
To return a value of such a type, allocate the right amount of
memory with <code class="literal">palloc</code>, fill in the allocated memory,
and return a pointer to it. (Also, if you just want to return the
same value as one of your input arguments that's of the same data type,
you can skip the extra <code class="literal">palloc</code> and just return the
pointer to the input value.)
</p>
<p> Finally, all variable-length types must also be passed
by reference. All variable-length types must begin
with a length field of exactly 4 bytes, and all data to
be stored within that type must be located in the memory
immediately following that length field. The
length field contains the total length of the structure,
that is, it includes the size of the length field
itself.
</p>
<div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Warning</h3>
<p> <span class="emphasis"><em>Never</em></span> modify the contents of a pass-by-reference input
value. If you do so you are likely to corrupt on-disk data, since
the pointer you are given may well point directly into a disk buffer.
The sole exception to this rule is explained in
<a href="xaggr.html" title="32.10.User-Defined Aggregates">Section32.10, “User-Defined Aggregates”</a>.
</p>
</div>
<p> As an example, we can define the type <code class="type">text</code> as
follows:
</p>
<pre class="programlisting">typedef struct {
int4 length;
char data[1];
} text;</pre>
<p>
Obviously, the data field declared here is not long enough to hold
all possible strings. Since it's impossible to declare a variable-size
structure in <acronym class="acronym">C</acronym>, we rely on the knowledge that the
<acronym class="acronym">C</acronym> compiler won't range-check array subscripts. We
just allocate the necessary amount of space and then access the array as
if it were declared the right length. (This is a common trick, which
you can read about in many textbooks about C.)
</p>
<p> When manipulating
variable-length types, we must be careful to allocate
the correct amount of memory and set the length field correctly.
For example, if we wanted to store 40 bytes in a <code class="structname">text</code>
structure, we might use a code fragment like this:
</p>
<pre class="programlisting">#include "postgres.h"
...
char buffer[40]; /* our source data */
...
text *destination = (text *) palloc(VARHDRSZ + 40);
destination->length = VARHDRSZ + 40;
memcpy(destination->data, buffer, 40);
...</pre>
<p>
<code class="literal">VARHDRSZ</code> is the same as <code class="literal">sizeof(int4)</code>, but
it's considered good style to use the macro <code class="literal">VARHDRSZ</code>
to refer to the size of the overhead for a variable-length type.
</p>
<p> <a href="xfunc-c.html#xfunc-c-type-table" title="Table32.1.Equivalent C Types for Built-In SQL Types">Table32.1, “Equivalent C Types for Built-In SQL Types”</a> specifies which C type
corresponds to which SQL type when writing a C-language function
that uses a built-in type of <span class="productname">PostgreSQL</span>.
The “<span class="quote">Defined In</span>” column gives the header file that
needs to be included to get the type definition. (The actual
definition may be in a different file that is included by the
listed file. It is recommended that users stick to the defined
interface.) Note that you should always include
<code class="filename">postgres.h</code> first in any source file, because
it declares a number of things that you will need anyway.
</p>
<div class="table">
<a name="xfunc-c-type-table"></a><p class="title"><b>Table32.1.Equivalent C Types for Built-In SQL Types</b></p>
<div class="table-contents"><table summary="Equivalent C Types for Built-In SQL Types" border="1">
<colgroup>
<col>
<col>
<col>
</colgroup>
<thead><tr>
<th> SQL Type
</th>
<th> C Type
</th>
<th> Defined In
</th>
</tr></thead>
<tbody>
<tr>
<td><code class="type">abstime</code></td>
<td><code class="type">AbsoluteTime</code></td>
<td><code class="filename">utils/nabstime.h</code></td>
</tr>
<tr>
<td><code class="type">boolean</code></td>
<td><code class="type">bool</code></td>
<td>
<code class="filename">postgres.h</code> (maybe compiler built-in)</td>
</tr>
<tr>
<td><code class="type">box</code></td>
<td><code class="type">BOX*</code></td>
<td><code class="filename">utils/geo_decls.h</code></td>
</tr>
<tr>
<td><code class="type">bytea</code></td>
<td><code class="type">bytea*</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">"char"</code></td>
<td><code class="type">char</code></td>
<td>(compiler built-in)</td>
</tr>
<tr>
<td><code class="type">character</code></td>
<td><code class="type">BpChar*</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">cid</code></td>
<td><code class="type">CommandId</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">date</code></td>
<td><code class="type">DateADT</code></td>
<td><code class="filename">utils/date.h</code></td>
</tr>
<tr>
<td>
<code class="type">smallint</code> (<code class="type">int2</code>)</td>
<td>
<code class="type">int2</code> or <code class="type">int16</code>
</td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">int2vector</code></td>
<td><code class="type">int2vector*</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td>
<code class="type">integer</code> (<code class="type">int4</code>)</td>
<td>
<code class="type">int4</code> or <code class="type">int32</code>
</td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td>
<code class="type">real</code> (<code class="type">float4</code>)</td>
<td><code class="type">float4*</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td>
<code class="type">double precision</code> (<code class="type">float8</code>)</td>
<td><code class="type">float8*</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">interval</code></td>
<td><code class="type">Interval*</code></td>
<td><code class="filename">utils/timestamp.h</code></td>
</tr>
<tr>
<td><code class="type">lseg</code></td>
<td><code class="type">LSEG*</code></td>
<td><code class="filename">utils/geo_decls.h</code></td>
</tr>
<tr>
<td><code class="type">name</code></td>
<td><code class="type">Name</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">oid</code></td>
<td><code class="type">Oid</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">oidvector</code></td>
<td><code class="type">oidvector*</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">path</code></td>
<td><code class="type">PATH*</code></td>
<td><code class="filename">utils/geo_decls.h</code></td>
</tr>
<tr>
<td><code class="type">point</code></td>
<td><code class="type">POINT*</code></td>
<td><code class="filename">utils/geo_decls.h</code></td>
</tr>
<tr>
<td><code class="type">regproc</code></td>
<td><code class="type">regproc</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">reltime</code></td>
<td><code class="type">RelativeTime</code></td>
<td><code class="filename">utils/nabstime.h</code></td>
</tr>
<tr>
<td><code class="type">text</code></td>
<td><code class="type">text*</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">tid</code></td>
<td><code class="type">ItemPointer</code></td>
<td><code class="filename">storage/itemptr.h</code></td>
</tr>
<tr>
<td><code class="type">time</code></td>
<td><code class="type">TimeADT</code></td>
<td><code class="filename">utils/date.h</code></td>
</tr>
<tr>
<td><code class="type">time with time zone</code></td>
<td><code class="type">TimeTzADT</code></td>
<td><code class="filename">utils/date.h</code></td>
</tr>
<tr>
<td><code class="type">timestamp</code></td>
<td><code class="type">Timestamp*</code></td>
<td><code class="filename">utils/timestamp.h</code></td>
</tr>
<tr>
<td><code class="type">tinterval</code></td>
<td><code class="type">TimeInterval</code></td>
<td><code class="filename">utils/nabstime.h</code></td>
</tr>
<tr>
<td><code class="type">varchar</code></td>
<td><code class="type">VarChar*</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
<tr>
<td><code class="type">xid</code></td>
<td><code class="type">TransactionId</code></td>
<td><code class="filename">postgres.h</code></td>
</tr>
</tbody>
</table></div>
</div>
<br class="table-break"><p> Now that we've gone over all of the possible structures
for base types, we can show some examples of real functions.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id707272"></a>32.9.3.Calling Conventions Version 0 for C-Language Functions</h3></div></div></div>
<p> We present the “<span class="quote">old style</span>” calling convention first [mdash ] although
this approach is now deprecated, it's easier to get a handle on
initially. In the version-0 method, the arguments and result
of the C function are just declared in normal C style, but being
careful to use the C representation of each SQL data type as shown
above.
</p>
<p> Here are some examples:
</p>
<pre class="programlisting">#include "postgres.h"
#include <string.h>
/* by value */
int
add_one(int arg)
{
return arg + 1;
}
/* by reference, fixed length */
float8 *
add_one_float8(float8 *arg)
{
float8 *result = (float8 *) palloc(sizeof(float8));
*result = *arg + 1.0;
return result;
}
Point *
makepoint(Point *pointx, Point *pointy)
{
Point *new_point = (Point *) palloc(sizeof(Point));
new_point->x = pointx->x;
new_point->y = pointy->y;
return new_point;
}
/* by reference, variable length */
text *
copytext(text *t)
{
/*
* VARSIZE is the total size of the struct in bytes.
*/
text *new_t = (text *) palloc(VARSIZE(t));
VARATT_SIZEP(new_t) = VARSIZE(t);
/*
* VARDATA is a pointer to the data region of the struct.
*/
memcpy((void *) VARDATA(new_t), /* destination */
(void *) VARDATA(t), /* source */
VARSIZE(t)-VARHDRSZ); /* how many bytes */
return new_t;
}
text *
concat_text(text *arg1, text *arg2)
{
int32 new_text_size = VARSIZE(arg1) + VARSIZE(arg2) - VARHDRSZ;
text *new_text = (text *) palloc(new_text_size);
VARATT_SIZEP(new_text) = new_text_size;
memcpy(VARDATA(new_text), VARDATA(arg1), VARSIZE(arg1)-VARHDRSZ);
memcpy(VARDATA(new_text) + (VARSIZE(arg1)-VARHDRSZ),
VARDATA(arg2), VARSIZE(arg2)-VARHDRSZ);
return new_text;
}</pre>
<p>
</p>
<p> Supposing that the above code has been prepared in file
<code class="filename">funcs.c</code> and compiled into a shared object,
we could define the functions to <span class="productname">PostgreSQL</span>
with commands like this:
</p>
<pre class="programlisting">CREATE FUNCTION add_one(integer) RETURNS integer
AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'add_one'
LANGUAGE C STRICT;
-- note overloading of SQL function name "add_one"
CREATE FUNCTION add_one(double precision) RETURNS double precision
AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'add_one_float8'
LANGUAGE C STRICT;
CREATE FUNCTION makepoint(point, point) RETURNS point
AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'makepoint'
LANGUAGE C STRICT;
CREATE FUNCTION copytext(text) RETURNS text
AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'copytext'
LANGUAGE C STRICT;
CREATE FUNCTION concat_text(text, text) RETURNS text
AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'concat_text'
LANGUAGE C STRICT;</pre>
<p>
</p>
<p> Here, <em class="replaceable"><code>DIRECTORY</code></em> stands for the
directory of the shared library file (for instance the
<span class="productname">PostgreSQL</span> tutorial directory, which
contains the code for the examples used in this section).
(Better style would be to use just <code class="literal">'funcs'</code> in the
<code class="literal">AS</code> clause, after having added
<em class="replaceable"><code>DIRECTORY</code></em> to the search path. In any
case, we may omit the system-specific extension for a shared
library, commonly <code class="literal">.so</code> or
<code class="literal">.sl</code>.)
</p>
<p> Notice that we have specified the functions as “<span class="quote">strict</span>”,
meaning that
the system should automatically assume a null result if any input
value is null. By doing this, we avoid having to check for null inputs
in the function code. Without this, we'd have to check for null values
explicitly, by checking for a null pointer for each
pass-by-reference argument. (For pass-by-value arguments, we don't
even have a way to check!)
</p>
<p> Although this calling convention is simple to use,
it is not very portable; on some architectures there are problems
with passing data types that are smaller than <code class="type">int</code> this way. Also, there is
no simple way to return a null result, nor to cope with null arguments
in any way other than making the function strict. The version-1
convention, presented next, overcomes these objections.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id707493"></a>32.9.4.Calling Conventions Version 1 for C-Language Functions</h3></div></div></div>
<p> The version-1 calling convention relies on macros to suppress most
of the complexity of passing arguments and results. The C declaration
of a version-1 function is always
</p>
<pre class="programlisting">Datum funcname(PG_FUNCTION_ARGS)</pre>
<p>
In addition, the macro call
</p>
<pre class="programlisting">PG_FUNCTION_INFO_V1(funcname);</pre>
<p>
must appear in the same source file. (Conventionally. it's
written just before the function itself.) This macro call is not
needed for <code class="literal">internal</code>-language functions, since
<span class="productname">PostgreSQL</span> assumes that all internal functions
use the version-1 convention. It is, however, required for
dynamically-loaded functions.
</p>
<p> In a version-1 function, each actual argument is fetched using a
<code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code>
macro that corresponds to the argument's data type, and the
result is returned using a
<code class="function">PG_RETURN_<em class="replaceable"><code>xxx</code></em>()</code>
macro for the return type.
<code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code>
takes as its argument the number of the function argument to
fetch, where the count starts at 0.
<code class="function">PG_RETURN_<em class="replaceable"><code>xxx</code></em>()</code>
takes as its argument the actual value to return.
</p>
<p> Here we show the same functions as above, coded in version-1 style:
</p>
<pre class="programlisting">#include "postgres.h"
#include <string.h>
#include "fmgr.h"
/* by value */
PG_FUNCTION_INFO_V1(add_one);
Datum
add_one(PG_FUNCTION_ARGS)
{
int32 arg = PG_GETARG_INT32(0);
PG_RETURN_INT32(arg + 1);
}
/* by reference, fixed length */
PG_FUNCTION_INFO_V1(add_one_float8);
Datum
add_one_float8(PG_FUNCTION_ARGS)
{
/* The macros for FLOAT8 hide its pass-by-reference nature. */
float8 arg = PG_GETARG_FLOAT8(0);
PG_RETURN_FLOAT8(arg + 1.0);
}
PG_FUNCTION_INFO_V1(makepoint);
Datum
makepoint(PG_FUNCTION_ARGS)
{
/* Here, the pass-by-reference nature of Point is not hidden. */
Point *pointx = PG_GETARG_POINT_P(0);
Point *pointy = PG_GETARG_POINT_P(1);
Point *new_point = (Point *) palloc(sizeof(Point));
new_point->x = pointx->x;
new_point->y = pointy->y;
PG_RETURN_POINT_P(new_point);
}
/* by reference, variable length */
PG_FUNCTION_INFO_V1(copytext);
Datum
copytext(PG_FUNCTION_ARGS)
{
text *t = PG_GETARG_TEXT_P(0);
/*
* VARSIZE is the total size of the struct in bytes.
*/
text *new_t = (text *) palloc(VARSIZE(t));
VARATT_SIZEP(new_t) = VARSIZE(t);
/*
* VARDATA is a pointer to the data region of the struct.
*/
memcpy((void *) VARDATA(new_t), /* destination */
(void *) VARDATA(t), /* source */
VARSIZE(t)-VARHDRSZ); /* how many bytes */
PG_RETURN_TEXT_P(new_t);
}
PG_FUNCTION_INFO_V1(concat_text);
Datum
concat_text(PG_FUNCTION_ARGS)
{
text *arg1 = PG_GETARG_TEXT_P(0);
text *arg2 = PG_GETARG_TEXT_P(1);
int32 new_text_size = VARSIZE(arg1) + VARSIZE(arg2) - VARHDRSZ;
text *new_text = (text *) palloc(new_text_size);
VARATT_SIZEP(new_text) = new_text_size;
memcpy(VARDATA(new_text), VARDATA(arg1), VARSIZE(arg1)-VARHDRSZ);
memcpy(VARDATA(new_text) + (VARSIZE(arg1)-VARHDRSZ),
VARDATA(arg2), VARSIZE(arg2)-VARHDRSZ);
PG_RETURN_TEXT_P(new_text);
}</pre>
<p>
</p>
<p> The <code class="command">CREATE FUNCTION</code> commands are the same as
for the version-0 equivalents.
</p>
<p> At first glance, the version-1 coding conventions may appear to
be just pointless obscurantism. They do, however, offer a number
of improvements, because the macros can hide unnecessary detail.
An example is that in coding <code class="function">add_one_float8</code>, we no longer need to
be aware that <code class="type">float8</code> is a pass-by-reference type. Another
example is that the <code class="literal">GETARG</code> macros for variable-length types allow
for more efficient fetching of “<span class="quote">toasted</span>” (compressed or
out-of-line) values.
</p>
<p> One big improvement in version-1 functions is better handling of null
inputs and results. The macro <code class="function">PG_ARGISNULL(<em class="replaceable"><code>n</code></em>)</code>
allows a function to test whether each input is null. (Of course, doing
this is only necessary in functions not declared “<span class="quote">strict</span>”.)
As with the
<code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code> macros,
the input arguments are counted beginning at zero. Note that one
should refrain from executing
<code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code> until
one has verified that the argument isn't null.
To return a null result, execute <code class="function">PG_RETURN_NULL()</code>;
this works in both strict and nonstrict functions.
</p>
<p> Other options provided in the new-style interface are two
variants of the
<code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>()</code>
macros. The first of these,
<code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>_COPY()</code>,
guarantees to return a copy of the specified argument that is
safe for writing into. (The normal macros will sometimes return a
pointer to a value that is physically stored in a table, which
must not be written to. Using the
<code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>_COPY()</code>
macros guarantees a writable result.)
The second variant consists of the
<code class="function">PG_GETARG_<em class="replaceable"><code>xxx</code></em>_SLICE()</code>
macros which take three arguments. The first is the number of the
function argument (as above). The second and third are the offset and
length of the segment to be returned. Offsets are counted from
zero, and a negative length requests that the remainder of the
value be returned. These macros provide more efficient access to
parts of large values in the case where they have storage type
“<span class="quote">external</span>”. (The storage type of a column can be specified using
<code class="literal">ALTER TABLE <em class="replaceable"><code>tablename</code></em> ALTER
COLUMN <em class="replaceable"><code>colname</code></em> SET STORAGE
<em class="replaceable"><code>storagetype</code></em></code>. <em class="replaceable"><code>storagetype</code></em> is one of
<code class="literal">plain</code>, <code class="literal">external</code>, <code class="literal">extended</code>,
or <code class="literal">main</code>.)
</p>
<p> Finally, the version-1 function call conventions make it possible
to return set results (<a href="xfunc-c.html#xfunc-c-return-set" title="32.9.10.Returning Sets from C-Language Functions">Section32.9.10, “Returning Sets from C-Language Functions”</a>) and
implement trigger functions (<a href="triggers.html" title="Chapter33.Triggers">Chapter33, <i>Triggers</i></a>) and
procedural-language call handlers (<a href="plhandler.html" title="Chapter46.Writing A Procedural Language Handler">Chapter46, <i>Writing A Procedural Language Handler</i></a>). Version-1 code is also more
portable than version-0, because it does not break restrictions
on function call protocol in the C standard. For more details
see <code class="filename">src/backend/utils/fmgr/README</code> in the
source distribution.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id707920"></a>32.9.5.Writing Code</h3></div></div></div>
<p> Before we turn to the more advanced topics, we should discuss
some coding rules for <span class="productname">PostgreSQL</span>
C-language functions. While it may be possible to load functions
written in languages other than C into
<span class="productname">PostgreSQL</span>, this is usually difficult
(when it is possible at all) because other languages, such as
C++, FORTRAN, or Pascal often do not follow the same calling
convention as C. That is, other languages do not pass argument
and return values between functions in the same way. For this
reason, we will assume that your C-language functions are
actually written in C.
</p>
<p> The basic rules for writing and building C functions are as follows:
</p>
<div class="itemizedlist"><ul type="disc">
<li><p> Use <code class="literal">pg_config
--includedir-server</code><a name="id707965"></a>
to find out where the <span class="productname">PostgreSQL</span> server header
files are installed on your system (or the system that your
users will be running on). This option is new with
<span class="productname">PostgreSQL</span> 7.2. For
<span class="productname">PostgreSQL</span> 7.1 you should use the option
<code class="option">--includedir</code>. (<code class="command">pg_config</code>
will exit with a non-zero status if it encounters an unknown
option.) For releases prior to 7.1 you will have to guess,
but since that was before the current calling conventions were
introduced, it is unlikely that you want to support those
releases.
</p></li>
<li><p> When allocating memory, use the
<span class="productname">PostgreSQL</span> functions
<code class="function">palloc</code><a name="id708032"></a> and <code class="function">pfree</code><a name="id708045"></a>
instead of the corresponding C library functions
<code class="function">malloc</code> and <code class="function">free</code>.
The memory allocated by <code class="function">palloc</code> will be
freed automatically at the end of each transaction, preventing
memory leaks.
</p></li>
<li><p> Always zero the bytes of your structures using
<code class="function">memset</code>. Without this, it's difficult to
support hash indexes or hash joins, as you must pick out only
the significant bits of your data structure to compute a hash.
Even if you initialize all fields of your structure, there may be
alignment padding (holes in the structure) that may contain
garbage values.
</p></li>
<li><p> Most of the internal <span class="productname">PostgreSQL</span>
types are declared in <code class="filename">postgres.h</code>, while
the function manager interfaces
(<code class="symbol">PG_FUNCTION_ARGS</code>, etc.) are in
<code class="filename">fmgr.h</code>, so you will need to include at
least these two files. For portability reasons it's best to
include <code class="filename">postgres.h</code> <span class="emphasis"><em>first</em></span>,
before any other system or user header files. Including
<code class="filename">postgres.h</code> will also include
<code class="filename">elog.h</code> and <code class="filename">palloc.h</code>
for you.
</p></li>
<li><p> Symbol names defined within object files must not conflict
with each other or with symbols defined in the
<span class="productname">PostgreSQL</span> server executable. You
will have to rename your functions or variables if you get
error messages to this effect.
</p></li>
<li><p> Compiling and linking your code so that it can be dynamically
loaded into <span class="productname">PostgreSQL</span> always
requires special flags. See <a href="xfunc-c.html#dfunc" title="32.9.6.Compiling and Linking Dynamically-Loaded Functions">Section32.9.6, “Compiling and Linking Dynamically-Loaded Functions”</a> for a
detailed explanation of how to do it for your particular
operating system.
</p></li>
</ul></div>
<p>
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="dfunc"></a>32.9.6.Compiling and Linking Dynamically-Loaded Functions</h3></div></div></div>
<p> Before you are able to use your
<span class="productname">PostgreSQL</span> extension functions written in
C, they must be compiled and linked in a special way to produce a
file that can be dynamically loaded by the server. To be precise, a
<em class="firstterm">shared library</em> needs to be
created.<a name="id708224"></a>
</p>
<p> For information beyond what is contained in this section
you should read the documentation of your
operating system, in particular the manual pages for the C compiler,
<code class="command">cc</code>, and the link editor, <code class="command">ld</code>.
In addition, the <span class="productname">PostgreSQL</span> source code
contains several working examples in the
<code class="filename">contrib</code> directory. If you rely on these
examples you will make your modules dependent on the availability
of the <span class="productname">PostgreSQL</span> source code, however.
</p>
<p> Creating shared libraries is generally analogous to linking
executables: first the source files are compiled into object files,
then the object files are linked together. The object files need to
be created as <em class="firstterm">position-independent code</em>
(<acronym class="acronym">PIC</acronym>),<a name="id708288"></a> which
conceptually means that they can be placed at an arbitrary location
in memory when they are loaded by the executable. (Object files
intended for executables are usually not compiled that way.) The
command to link a shared library contains special flags to
distinguish it from linking an executable (at least in theory
[mdash ] on some systems the practice is much uglier).
</p>
<p> In the following examples we assume that your source code is in a
file <code class="filename">foo.c</code> and we will create a shared library
<code class="filename">foo.so</code>. The intermediate object file will be
called <code class="filename">foo.o</code> unless otherwise noted. A shared
library can contain more than one object file, but we only use one
here.
</p>
<div class="variablelist"><dl>
<dt><span class="term"><span class="systemitem">BSD/OS</span></span></dt>
<dd>
<p> The compiler flag to create <acronym class="acronym">PIC</acronym> is
<code class="option">-fpic</code>. The linker flag to create shared
libraries is <code class="option">-shared</code>.
</p>
<pre class="programlisting">gcc -fpic -c foo.c
ld -shared -o foo.so foo.o</pre>
<p>
This is applicable as of version 4.0 of
<span class="systemitem">BSD/OS</span>.
</p>
</dd>
<dt><span class="term"><span class="systemitem">FreeBSD</span></span></dt>
<dd>
<p> The compiler flag to create <acronym class="acronym">PIC</acronym> is
<code class="option">-fpic</code>. To create shared libraries the compiler
flag is <code class="option">-shared</code>.
</p>
<pre class="programlisting">gcc -fpic -c foo.c
gcc -shared -o foo.so foo.o</pre>
<p>
This is applicable as of version 3.0 of
<span class="systemitem">FreeBSD</span>.
</p>
</dd>
<dt><span class="term"><span class="systemitem">HP-UX</span></span></dt>
<dd>
<p> The compiler flag of the system compiler to create
<acronym class="acronym">PIC</acronym> is <code class="option">+z</code>. When using
<span class="application">GCC</span> it's <code class="option">-fpic</code>. The
linker flag for shared libraries is <code class="option">-b</code>. So
</p>
<pre class="programlisting">cc +z -c foo.c</pre>
<p>
or
</p>
<pre class="programlisting">gcc -fpic -c foo.c</pre>
<p>
and then
</p>
<pre class="programlisting">ld -b -o foo.sl foo.o</pre>
<p>
<span class="systemitem">HP-UX</span> uses the extension
<code class="filename">.sl</code> for shared libraries, unlike most other
systems.
</p>
</dd>
<dt><span class="term"><span class="systemitem">IRIX</span></span></dt>
<dd>
<p> <acronym class="acronym">PIC</acronym> is the default, no special compiler
options are necessary. The linker option to produce shared
libraries is <code class="option">-shared</code>.
</p>
<pre class="programlisting">cc -c foo.c
ld -shared -o foo.so foo.o</pre>
<p>
</p>
</dd>
<dt><span class="term"><span class="systemitem">Linux</span></span></dt>
<dd>
<p> The compiler flag to create <acronym class="acronym">PIC</acronym> is
<code class="option">-fpic</code>. On some platforms in some situations
<code class="option">-fPIC</code> must be used if <code class="option">-fpic</code>
does not work. Refer to the GCC manual for more information.
The compiler flag to create a shared library is
<code class="option">-shared</code>. A complete example looks like this:
</p>
<pre class="programlisting">cc -fpic -c foo.c
cc -shared -o foo.so foo.o</pre>
<p>
</p>
</dd>
<dt><span class="term"><span class="systemitem">MacOS X</span></span></dt>
<dd>
<p> Here is an example. It assumes the developer tools are installed.
</p>
<pre class="programlisting">cc -c foo.c
cc -bundle -flat_namespace -undefined suppress -o foo.so foo.o</pre>
<p>
</p>
</dd>
<dt><span class="term"><span class="systemitem">NetBSD</span></span></dt>
<dd>
<p> The compiler flag to create <acronym class="acronym">PIC</acronym> is
<code class="option">-fpic</code>. For <acronym class="acronym">ELF</acronym> systems, the
compiler with the flag <code class="option">-shared</code> is used to link
shared libraries. On the older non-ELF systems, <code class="literal">ld
-Bshareable</code> is used.
</p>
<pre class="programlisting">gcc -fpic -c foo.c
gcc -shared -o foo.so foo.o</pre>
<p>
</p>
</dd>
<dt><span class="term"><span class="systemitem">OpenBSD</span></span></dt>
<dd>
<p> The compiler flag to create <acronym class="acronym">PIC</acronym> is
<code class="option">-fpic</code>. <code class="literal">ld -Bshareable</code> is
used to link shared libraries.
</p>
<pre class="programlisting">gcc -fpic -c foo.c
ld -Bshareable -o foo.so foo.o</pre>
<p>
</p>
</dd>
<dt><span class="term"><span class="systemitem">Solaris</span></span></dt>
<dd>
<p> The compiler flag to create <acronym class="acronym">PIC</acronym> is
<code class="option">-KPIC</code> with the Sun compiler and
<code class="option">-fpic</code> with <span class="application">GCC</span>. To
link shared libraries, the compiler option is
<code class="option">-G</code> with either compiler or alternatively
<code class="option">-shared</code> with <span class="application">GCC</span>.
</p>
<pre class="programlisting">cc -KPIC -c foo.c
cc -G -o foo.so foo.o</pre>
<p>
or
</p>
<pre class="programlisting">gcc -fpic -c foo.c
gcc -G -o foo.so foo.o</pre>
<p>
</p>
</dd>
<dt><span class="term"><span class="systemitem">Tru64 UNIX</span></span></dt>
<dd>
<p> <acronym class="acronym">PIC</acronym> is the default, so the compilation command
is the usual one. <code class="command">ld</code> with special options is
used to do the linking:
</p>
<pre class="programlisting">cc -c foo.c
ld -shared -expect_unresolved '*' -o foo.so foo.o</pre>
<p>
The same procedure is used with GCC instead of the system
compiler; no special options are required.
</p>
</dd>
<dt><span class="term"><span class="systemitem">UnixWare</span></span></dt>
<dd>
<p> The compiler flag to create <acronym class="acronym">PIC</acronym> is <code class="option">-K
PIC</code> with the SCO compiler and <code class="option">-fpic</code>
with <span class="productname">GCC</span>. To link shared libraries,
the compiler option is <code class="option">-G</code> with the SCO compiler
and <code class="option">-shared</code> with
<span class="productname">GCC</span>.
</p>
<pre class="programlisting">cc -K PIC -c foo.c
cc -G -o foo.so foo.o</pre>
<p>
or
</p>
<pre class="programlisting">gcc -fpic -c foo.c
gcc -shared -o foo.so foo.o</pre>
<p>
</p>
</dd>
</dl></div>
<div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Tip</h3>
<p> If this is too complicated for you, you should consider using
<a href="http://www.gnu.org/software/libtool/" target="_top"> <span class="productname">GNU Libtool</span></a>,
which hides the platform differences behind a uniform interface.
</p>
</div>
<p> The resulting shared library file can then be loaded into
<span class="productname">PostgreSQL</span>. When specifying the file name
to the <code class="command">CREATE FUNCTION</code> command, one must give it
the name of the shared library file, not the intermediate object file.
Note that the system's standard shared-library extension (usually
<code class="literal">.so</code> or <code class="literal">.sl</code>) can be omitted from
the <code class="command">CREATE FUNCTION</code> command, and normally should
be omitted for best portability.
</p>
<p> Refer back to <a href="xfunc-c.html#xfunc-c-dynload" title="32.9.1.Dynamic Loading">Section32.9.1, “Dynamic Loading”</a> about where the
server expects to find the shared library files.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="xfunc-c-pgxs"></a>32.9.7.Extension Building Infrastructure</h3></div></div></div>
<a name="id709032"></a><p> If you are thinking about distributing your
<span class="productname">PostgreSQL</span> extension modules, setting up a
portable build system for them can be fairly difficult. Therefore
the <span class="productname">PostgreSQL</span> installation provides a build
infrastructure for extensions, called <acronym class="acronym">PGXS</acronym>, so
that simple extension modules can be built simply against an
already installed server. Note that this infrastructure is not
intended to be a universal build system framework that can be used
to build all software interfacing to <span class="productname">PostgreSQL</span>;
it simply automates common build rules for simple server extension
modules. For more complicated packages, you need to write your
own build system.
</p>
<p> To use the infrastructure for your extension, you must write a
simple makefile. In that makefile, you need to set some variables
and finally include the global <acronym class="acronym">PGXS</acronym> makefile.
Here is an example that builds an extension module named
<code class="literal">isbn_issn</code> consisting of a shared library, an
SQL script, and a documentation text file:
</p>
<pre class="programlisting">MODULES = isbn_issn
DATA_built = isbn_issn.sql
DOCS = README.isbn_issn
PGXS := $(shell pg_config --pgxs)
include $(PGXS)</pre>
<p>
The last two lines should always be the same. Earlier in the
file, you assign variables or add custom
<span class="application">make</span> rules.
</p>
<p> The following variables can be set:
</p>
<div class="variablelist"><dl>
<dt><span class="term"><code class="varname">MODULES</code></span></dt>
<dd><p> list of shared objects to be built from source file with same
stem (do not include suffix in this list)
</p></dd>
<dt><span class="term"><code class="varname">DATA</code></span></dt>
<dd><p> random files to install into <code class="literal"><em class="replaceable"><code>prefix</code></em>/share/contrib</code>
</p></dd>
<dt><span class="term"><code class="varname">DATA_built</code></span></dt>
<dd><p> random files to install into
<code class="literal"><em class="replaceable"><code>prefix</code></em>/share/contrib</code>,
which need to be built first
</p></dd>
<dt><span class="term"><code class="varname">DOCS</code></span></dt>
<dd><p> random files to install under
<code class="literal"><em class="replaceable"><code>prefix</code></em>/doc/contrib</code>
</p></dd>
<dt><span class="term"><code class="varname">SCRIPTS</code></span></dt>
<dd><p> script files (not binaries) to install into
<code class="literal"><em class="replaceable"><code>prefix</code></em>/bin</code>
</p></dd>
<dt><span class="term"><code class="varname">SCRIPTS_built</code></span></dt>
<dd><p> script files (not binaries) to install into
<code class="literal"><em class="replaceable"><code>prefix</code></em>/bin</code>,
which need to be built first
</p></dd>
<dt><span class="term"><code class="varname">REGRESS</code></span></dt>
<dd><p> list of regression test cases (without suffix)
</p></dd>
</dl></div>
<p>
or at most one of these two:
</p>
<div class="variablelist"><dl>
<dt><span class="term"><code class="varname">PROGRAM</code></span></dt>
<dd><p> a binary program to build (list objects files in <code class="varname">OBJS</code>)
</p></dd>
<dt><span class="term"><code class="varname">MODULE_big</code></span></dt>
<dd><p> a shared object to build (list object files in <code class="varname">OBJS</code>)
</p></dd>
</dl></div>
<p>
The following can also be set:
</p>
<div class="variablelist"><dl>
<dt><span class="term"><code class="varname">EXTRA_CLEAN</code></span></dt>
<dd><p> extra files to remove in <code class="literal">make clean</code>
</p></dd>
<dt><span class="term"><code class="varname">PG_CPPFLAGS</code></span></dt>
<dd><p> will be added to <code class="varname">CPPFLAGS</code>
</p></dd>
<dt><span class="term"><code class="varname">PG_LIBS</code></span></dt>
<dd><p> will be added to <code class="varname">PROGRAM</code> link line
</p></dd>
<dt><span class="term"><code class="varname">SHLIB_LINK</code></span></dt>
<dd><p> will be added to <code class="varname">MODULE_big</code> link line
</p></dd>
</dl></div>
<p>
</p>
<p> Put this makefile as <code class="literal">Makefile</code> in the directory
which holds your extension. Then you can do
<code class="literal">make</code> to compile, and later <code class="literal">make
install</code> to install your module. The extension is
compiled and installed for the
<span class="productname">PostgreSQL</span> installation that
corresponds to the first <code class="command">pg_config</code> command
found in your path.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id709371"></a>32.9.8.Composite-Type Arguments in C-Language Functions</h3></div></div></div>
<p> Composite types do not have a fixed layout like C structures.
Instances of a composite type may contain null fields. In
addition, composite types that are part of an inheritance
hierarchy may have different fields than other members of the
same inheritance hierarchy. Therefore,
<span class="productname">PostgreSQL</span> provides a function
interface for accessing fields of composite types from C.
</p>
<p> Suppose we want to write a function to answer the query
</p>
<pre class="programlisting">SELECT name, c_overpaid(emp, 1500) AS overpaid
FROM emp
WHERE name = 'Bill' OR name = 'Sam';</pre>
<p>
Using call conventions version 0, we can define
<code class="function">c_overpaid</code> as:
</p>
<pre class="programlisting">#include "postgres.h"
#include "executor/executor.h" /* for GetAttributeByName() */
bool
c_overpaid(HeapTupleHeader t, /* the current row of emp */
int32 limit)
{
bool isnull;
int32 salary;
salary = DatumGetInt32(GetAttributeByName(t, "salary", &isnull));
if (isnull)
return false;
return salary > limit;
}</pre>
<p>
In version-1 coding, the above would look like this:
</p>
<pre class="programlisting">#include "postgres.h"
#include "executor/executor.h" /* for GetAttributeByName() */
PG_FUNCTION_INFO_V1(c_overpaid);
Datum
c_overpaid(PG_FUNCTION_ARGS)
{
HeapTupleHeader t = PG_GETARG_HEAPTUPLEHEADER(0);
int32 limit = PG_GETARG_INT32(1);
bool isnull;
Datum salary;
salary = GetAttributeByName(t, "salary", &isnull);
if (isnull)
PG_RETURN_BOOL(false);
/* Alternatively, we might prefer to do PG_RETURN_NULL() for null salary. */
PG_RETURN_BOOL(DatumGetInt32(salary) > limit);
}</pre>
<p>
</p>
<p> <code class="function">GetAttributeByName</code> is the
<span class="productname">PostgreSQL</span> system function that
returns attributes out of the specified row. It has
three arguments: the argument of type <code class="type">HeapTupleHeader</code> passed
into
the function, the name of the desired attribute, and a
return parameter that tells whether the attribute
is null. <code class="function">GetAttributeByName</code> returns a <code class="type">Datum</code>
value that you can convert to the proper data type by using the
appropriate <code class="function">DatumGet<em class="replaceable"><code>XXX</code></em>()</code>
macro. Note that the return value is meaningless if the null flag is
set; always check the null flag before trying to do anything with the
result.
</p>
<p> There is also <code class="function">GetAttributeByNum</code>, which selects
the target attribute by column number instead of name.
</p>
<p> The following command declares the function
<code class="function">c_overpaid</code> in SQL:
</p>
<pre class="programlisting">CREATE FUNCTION c_overpaid(emp, integer) RETURNS boolean
AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'c_overpaid'
LANGUAGE C STRICT;</pre>
<p>
Notice we have used <code class="literal">STRICT</code> so that we did not have to
check whether the input arguments were NULL.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id709538"></a>32.9.9.Returning Rows (Composite Types) from C-Language Functions</h3></div></div></div>
<p> To return a row or composite-type value from a C-language
function, you can use a special API that provides macros and
functions to hide most of the complexity of building composite
data types. To use this API, the source file must include:
</p>
<pre class="programlisting">#include "funcapi.h"</pre>
<p>
</p>
<p> There are two ways you can build a composite data value (henceforth
a “<span class="quote">tuple</span>”): you can build it from an array of Datum values,
or from an array of C strings that can be passed to the input
conversion functions of the tuple's column data types. In either
case, you first need to obtain or construct a <code class="structname">TupleDesc</code>
descriptor for the tuple structure. When working with Datums, you
pass the <code class="structname">TupleDesc</code> to <code class="function">BlessTupleDesc</code>,
and then call <code class="function">heap_form_tuple</code> for each row. When working
with C strings, you pass the <code class="structname">TupleDesc</code> to
<code class="function">TupleDescGetAttInMetadata</code>, and then call
<code class="function">BuildTupleFromCStrings</code> for each row. In the case of a
function returning a set of tuples, the setup steps can all be done
once during the first call of the function.
</p>
<p> Several helper functions are available for setting up the needed
<code class="structname">TupleDesc</code>. The recommended way to do this in most
functions returning composite values is to call
</p>
<pre class="programlisting">TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo,
Oid *resultTypeId,
TupleDesc *resultTupleDesc)</pre>
<p>
passing the same <code class="literal">fcinfo</code> struct passed to the calling function
itself. (This of course requires that you use the version-1
calling conventions.) <code class="varname">resultTypeId</code> can be specified
as <code class="literal">NULL</code> or as the address of a local variable to receive the
function's result type OID. <code class="varname">resultTupleDesc</code> should be the
address of a local <code class="structname">TupleDesc</code> variable. Check that the
result is <code class="literal">TYPEFUNC_COMPOSITE</code>; if so,
<code class="varname">resultTupleDesc</code> has been filled with the needed
<code class="structname">TupleDesc</code>. (If it is not, you can report an error along
the lines of “<span class="quote">function returning record called in context that
cannot accept type record</span>”.)
</p>
<div class="tip" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Tip</h3>
<p> <code class="function">get_call_result_type</code> can resolve the actual type of a
polymorphic function result; so it is useful in functions that return
scalar polymorphic results, not only functions that return composites.
The <code class="varname">resultTypeId</code> output is primarily useful for functions
returning polymorphic scalars.
</p>
</div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p> <code class="function">get_call_result_type</code> has a sibling
<code class="function">get_expr_result_type</code>, which can be used to resolve the
expected output type for a function call represented by an expression
tree. This can be used when trying to determine the result type from
outside the function itself. There is also
<code class="function">get_func_result_type</code>, which can be used when only the
function's OID is available. However these functions are not able
to deal with functions declared to return <code class="structname">record</code>, and
<code class="function">get_func_result_type</code> cannot resolve polymorphic types,
so you should preferentially use <code class="function">get_call_result_type</code>.
</p>
</div>
<p> Older, now-deprecated functions for obtaining
<code class="structname">TupleDesc</code>s are
</p>
<pre class="programlisting">TupleDesc RelationNameGetTupleDesc(const char *relname)</pre>
<p>
to get a <code class="structname">TupleDesc</code> for the row type of a named relation,
and
</p>
<pre class="programlisting">TupleDesc TypeGetTupleDesc(Oid typeoid, List *colaliases)</pre>
<p>
to get a <code class="structname">TupleDesc</code> based on a type OID. This can
be used to get a <code class="structname">TupleDesc</code> for a base or
composite type. It will not work for a function that returns
<code class="structname">record</code>, however, and it cannot resolve polymorphic
types.
</p>
<p> Once you have a <code class="structname">TupleDesc</code>, call
</p>
<pre class="programlisting">TupleDesc BlessTupleDesc(TupleDesc tupdesc)</pre>
<p>
if you plan to work with Datums, or
</p>
<pre class="programlisting">AttInMetadata *TupleDescGetAttInMetadata(TupleDesc tupdesc)</pre>
<p>
if you plan to work with C strings. If you are writing a function
returning set, you can save the results of these functions in the
<code class="structname">FuncCallContext</code> structure [mdash ] use the
<code class="structfield">tuple_desc</code> or <code class="structfield">attinmeta</code> field
respectively.
</p>
<p> When working with Datums, use
</p>
<pre class="programlisting">HeapTuple heap_form_tuple(TupleDesc tupdesc, Datum *values, bool *isnull)</pre>
<p>
to build a <code class="structname">HeapTuple</code> given user data in Datum form.
</p>
<p> When working with C strings, use
</p>
<pre class="programlisting">HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)</pre>
<p>
to build a <code class="structname">HeapTuple</code> given user data
in C string form. <code class="literal">values</code> is an array of C strings,
one for each attribute of the return row. Each C string should be in
the form expected by the input function of the attribute data
type. In order to return a null value for one of the attributes,
the corresponding pointer in the <em class="parameter"><code>values</code></em> array
should be set to <code class="symbol">NULL</code>. This function will need to
be called again for each row you return.
</p>
<p> Once you have built a tuple to return from your function, it
must be converted into a <code class="type">Datum</code>. Use
</p>
<pre class="programlisting">HeapTupleGetDatum(HeapTuple tuple)</pre>
<p>
to convert a <code class="structname">HeapTuple</code> into a valid Datum. This
<code class="type">Datum</code> can be returned directly if you intend to return
just a single row, or it can be used as the current return value
in a set-returning function.
</p>
<p> An example appears in the next section.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="xfunc-c-return-set"></a>32.9.10.Returning Sets from C-Language Functions</h3></div></div></div>
<p> There is also a special API that provides support for returning
sets (multiple rows) from a C-language function. A set-returning
function must follow the version-1 calling conventions. Also,
source files must include <code class="filename">funcapi.h</code>, as
above.
</p>
<p> A set-returning function (<acronym class="acronym">SRF</acronym>) is called
once for each item it returns. The <acronym class="acronym">SRF</acronym> must
therefore save enough state to remember what it was doing and
return the next item on each call.
The structure <code class="structname">FuncCallContext</code> is provided to help
control this process. Within a function, <code class="literal">fcinfo->flinfo->fn_extra</code>
is used to hold a pointer to <code class="structname">FuncCallContext</code>
across calls.
</p>
<pre class="programlisting">typedef struct
{
/*
* Number of times we've been called before
*
* call_cntr is initialized to 0 for you by SRF_FIRSTCALL_INIT(), and
* incremented for you every time SRF_RETURN_NEXT() is called.
*/
uint32 call_cntr;
/*
* OPTIONAL maximum number of calls
*
* max_calls is here for convenience only and setting it is optional.
* If not set, you must provide alternative means to know when the
* function is done.
*/
uint32 max_calls;
/*
* OPTIONAL pointer to result slot
*
* This is obsolete and only present for backwards compatibility, viz,
* user-defined SRFs that use the deprecated TupleDescGetSlot().
*/
TupleTableSlot *slot;
/*
* OPTIONAL pointer to miscellaneous user-provided context information
*
* user_fctx is for use as a pointer to your own data to retain
* arbitrary context information between calls of your function.
*/
void *user_fctx;
/*
* OPTIONAL pointer to struct containing attribute type input metadata
*
* attinmeta is for use when returning tuples (i.e., composite data types)
* and is not used when returning base data types. It is only needed
* if you intend to use BuildTupleFromCStrings() to create the return
* tuple.
*/
AttInMetadata *attinmeta;
/*
* memory context used for structures that must live for multiple calls
*
* multi_call_memory_ctx is set by SRF_FIRSTCALL_INIT() for you, and used
* by SRF_RETURN_DONE() for cleanup. It is the most appropriate memory
* context for any memory that is to be reused across multiple calls
* of the SRF.
*/
MemoryContext multi_call_memory_ctx;
/*
* OPTIONAL pointer to struct containing tuple description
*
* tuple_desc is for use when returning tuples (i.e. composite data types)
* and is only needed if you are going to build the tuples with
* heap_form_tuple() rather than with BuildTupleFromCStrings(). Note that
* the TupleDesc pointer stored here should usually have been run through
* BlessTupleDesc() first.
*/
TupleDesc tuple_desc;
} FuncCallContext;</pre>
<p>
</p>
<p> An <acronym class="acronym">SRF</acronym> uses several functions and macros that
automatically manipulate the <code class="structname">FuncCallContext</code>
structure (and expect to find it via <code class="literal">fn_extra</code>). Use
</p>
<pre class="programlisting">SRF_IS_FIRSTCALL()</pre>
<p>
to determine if your function is being called for the first or a
subsequent time. On the first call (only) use
</p>
<pre class="programlisting">SRF_FIRSTCALL_INIT()</pre>
<p>
to initialize the <code class="structname">FuncCallContext</code>. On every function call,
including the first, use
</p>
<pre class="programlisting">SRF_PERCALL_SETUP()</pre>
<p>
to properly set up for using the <code class="structname">FuncCallContext</code>
and clearing any previously returned data left over from the
previous pass.
</p>
<p> If your function has data to return, use
</p>
<pre class="programlisting">SRF_RETURN_NEXT(funcctx, result)</pre>
<p>
to return it to the caller. (<code class="literal">result</code> must be of type
<code class="type">Datum</code>, either a single value or a tuple prepared as
described above.) Finally, when your function is finished
returning data, use
</p>
<pre class="programlisting">SRF_RETURN_DONE(funcctx)</pre>
<p>
to clean up and end the <acronym class="acronym">SRF</acronym>.
</p>
<p> The memory context that is current when the <acronym class="acronym">SRF</acronym> is called is
a transient context that will be cleared between calls. This means
that you do not need to call <code class="function">pfree</code> on everything
you allocated using <code class="function">palloc</code>; it will go away anyway. However, if you want to allocate
any data structures to live across calls, you need to put them somewhere
else. The memory context referenced by
<code class="structfield">multi_call_memory_ctx</code> is a suitable location for any
data that needs to survive until the <acronym class="acronym">SRF</acronym> is finished running. In most
cases, this means that you should switch into
<code class="structfield">multi_call_memory_ctx</code> while doing the first-call setup.
</p>
<p> A complete pseudo-code example looks like the following:
</p>
<pre class="programlisting">Datum
my_set_returning_function(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
Datum result;
MemoryContext oldcontext;
<em class="replaceable"><code>further declarations as needed</code></em>
if (SRF_IS_FIRSTCALL())
{
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* One-time setup code appears here: */
<em class="replaceable"><code>user code</code></em>
<em class="replaceable"><code>if returning composite</code></em>
<em class="replaceable"><code>build TupleDesc, and perhaps AttInMetadata</code></em>
<em class="replaceable"><code>endif returning composite</code></em>
<em class="replaceable"><code>user code</code></em>
MemoryContextSwitchTo(oldcontext);
}
/* Each-time setup code appears here: */
<em class="replaceable"><code>user code</code></em>
funcctx = SRF_PERCALL_SETUP();
<em class="replaceable"><code>user code</code></em>
/* this is just one way we might test whether we are done: */
if (funcctx->call_cntr < funcctx->max_calls)
{
/* Here we want to return another item: */
<em class="replaceable"><code>user code</code></em>
<em class="replaceable"><code>obtain result Datum</code></em>
SRF_RETURN_NEXT(funcctx, result);
}
else
{
/* Here we are done returning items and just need to clean up: */
<em class="replaceable"><code>user code</code></em>
SRF_RETURN_DONE(funcctx);
}
}</pre>
<p>
</p>
<p> A complete example of a simple <acronym class="acronym">SRF</acronym> returning a composite type
looks like:
</p>
<pre class="programlisting">PG_FUNCTION_INFO_V1(retcomposite);
Datum
retcomposite(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
int call_cntr;
int max_calls;
TupleDesc tupdesc;
AttInMetadata *attinmeta;
/* stuff done only on the first call of the function */
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
/* create a function context for cross-call persistence */
funcctx = SRF_FIRSTCALL_INIT();
/* switch to memory context appropriate for multiple function calls */
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* total number of tuples to be returned */
funcctx->max_calls = PG_GETARG_UINT32(0);
/* Build a tuple descriptor for our result type */
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
/*
* generate attribute metadata needed later to produce tuples from raw
* C strings
*/
attinmeta = TupleDescGetAttInMetadata(tupdesc);
funcctx->attinmeta = attinmeta;
MemoryContextSwitchTo(oldcontext);
}
/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SETUP();
call_cntr = funcctx->call_cntr;
max_calls = funcctx->max_calls;
attinmeta = funcctx->attinmeta;
if (call_cntr < max_calls) /* do when there is more left to send */
{
char **values;
HeapTuple tuple;
Datum result;
/*
* Prepare a values array for building the returned tuple.
* This should be an array of C strings which will
* be processed later by the type input functions.
*/
values = (char **) palloc(3 * sizeof(char *));
values[0] = (char *) palloc(16 * sizeof(char));
values[1] = (char *) palloc(16 * sizeof(char));
values[2] = (char *) palloc(16 * sizeof(char));
snprintf(values[0], 16, "%d", 1 * PG_GETARG_INT32(1));
snprintf(values[1], 16, "%d", 2 * PG_GETARG_INT32(1));
snprintf(values[2], 16, "%d", 3 * PG_GETARG_INT32(1));
/* build a tuple */
tuple = BuildTupleFromCStrings(attinmeta, values);
/* make the tuple into a datum */
result = HeapTupleGetDatum(tuple);
/* clean up (this is not really necessary) */
pfree(values[0]);
pfree(values[1]);
pfree(values[2]);
pfree(values);
SRF_RETURN_NEXT(funcctx, result);
}
else /* do when there is no more left */
{
SRF_RETURN_DONE(funcctx);
}
}</pre>
<p>
One way to declare this function in SQL is:
</p>
<pre class="programlisting">CREATE TYPE __retcomposite AS (f1 integer, f2 integer, f3 integer);
CREATE OR REPLACE FUNCTION retcomposite(integer, integer)
RETURNS SETOF __retcomposite
AS '<em class="replaceable"><code>filename</code></em>', 'retcomposite'
LANGUAGE C IMMUTABLE STRICT;</pre>
<p>
A different way is to use OUT parameters:
</p>
<pre class="programlisting">CREATE OR REPLACE FUNCTION retcomposite(IN integer, IN integer,
OUT f1 integer, OUT f2 integer, OUT f3 integer)
RETURNS SETOF record
AS '<em class="replaceable"><code>filename</code></em>', 'retcomposite'
LANGUAGE C IMMUTABLE STRICT;</pre>
<p>
Notice that in this method the output type of the function is formally
an anonymous <code class="structname">record</code> type.
</p>
<p> The directory <code class="filename">contrib/tablefunc</code> in the source
distribution contains more examples of set-returning functions.
</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage"><div><div><h3 class="title">
<a name="id710389"></a>32.9.11.Polymorphic Arguments and Return Types</h3></div></div></div>
<p> C-language functions may be declared to accept and
return the polymorphic types
<code class="type">anyelement</code> and <code class="type">anyarray</code>.
See <a href="extend-type-system.html#extend-types-polymorphic" title="32.2.5.Polymorphic Types">Section32.2.5, “Polymorphic Types”</a> for a more detailed explanation
of polymorphic functions. When function arguments or return types
are defined as polymorphic types, the function author cannot know
in advance what data type it will be called with, or
need to return. There are two routines provided in <code class="filename">fmgr.h</code>
to allow a version-1 C function to discover the actual data types
of its arguments and the type it is expected to return. The routines are
called <code class="literal">get_fn_expr_rettype(FmgrInfo *flinfo)</code> and
<code class="literal">get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)</code>.
They return the result or argument type OID, or <code class="symbol">InvalidOid</code> if the
information is not available.
The structure <code class="literal">flinfo</code> is normally accessed as
<code class="literal">fcinfo->flinfo</code>. The parameter <code class="literal">argnum</code>
is zero based. <code class="function">get_call_result_type</code> can also be used
as an alternative to <code class="function">get_fn_expr_rettype</code>.
</p>
<p> For example, suppose we want to write a function to accept a single
element of any type, and return a one-dimensional array of that type:
</p>
<pre class="programlisting">PG_FUNCTION_INFO_V1(make_array);
Datum
make_array(PG_FUNCTION_ARGS)
{
ArrayType *result;
Oid element_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
Datum element;
int16 typlen;
bool typbyval;
char typalign;
int ndims;
int dims[MAXDIM];
int lbs[MAXDIM];
if (!OidIsValid(element_type))
elog(ERROR, "could not determine data type of input");
/* get the provided element */
element = PG_GETARG_DATUM(0);
/* we have one dimension */
ndims = 1;
/* and one element */
dims[0] = 1;
/* and lower bound is 1 */
lbs[0] = 1;
/* get required info about the element type */
get_typlenbyvalalign(element_type, &typlen, &typbyval, &typalign);
/* now build the array */
result = construct_md_array(&element, ndims, dims, lbs,
element_type, typlen, typbyval, typalign);
PG_RETURN_ARRAYTYPE_P(result);
}</pre>
<p>
</p>
<p> The following command declares the function
<code class="function">make_array</code> in SQL:
</p>
<pre class="programlisting">CREATE FUNCTION make_array(anyelement) RETURNS anyarray
AS '<em class="replaceable"><code>DIRECTORY</code></em>/funcs', 'make_array'
LANGUAGE C STRICT;</pre>
<p>
Note the use of <code class="literal">STRICT</code>; this is essential
since the code is not bothering to test for a null input.
</p>
</div>
</div></body>
</html>
|