gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

613 lines
30KB

  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>64.3. Extensibility</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets V1.79.1" /><link rel="prev" href="gist-builtin-opclasses.html" title="64.2. Built-in Operator Classes" /><link rel="next" href="gist-implementation.html" title="64.4. Implementation" /></head><body><div xmlns="http://www.w3.org/TR/xhtml1/transitional" class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">64.3. Extensibility</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="gist-builtin-opclasses.html" title="64.2. Built-in Operator Classes">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="gist.html" title="Chapter 64. GiST Indexes">Up</a></td><th width="60%" align="center">Chapter 64. GiST Indexes</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 12.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="gist-implementation.html" title="64.4. Implementation">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="GIST-EXTENSIBILITY"><div class="titlepage"><div><div><h2 class="title" style="clear: both">64.3. Extensibility</h2></div></div></div><p>
  3. Traditionally, implementing a new index access method meant a lot of
  4. difficult work. It was necessary to understand the inner workings of the
  5. database, such as the lock manager and Write-Ahead Log. The
  6. <acronym class="acronym">GiST</acronym> interface has a high level of abstraction,
  7. requiring the access method implementer only to implement the semantics of
  8. the data type being accessed. The <acronym class="acronym">GiST</acronym> layer itself
  9. takes care of concurrency, logging and searching the tree structure.
  10. </p><p>
  11. This extensibility should not be confused with the extensibility of the
  12. other standard search trees in terms of the data they can handle. For
  13. example, <span class="productname">PostgreSQL</span> supports extensible B-trees
  14. and hash indexes. That means that you can use
  15. <span class="productname">PostgreSQL</span> to build a B-tree or hash over any
  16. data type you want. But B-trees only support range predicates
  17. (<code class="literal">&lt;</code>, <code class="literal">=</code>, <code class="literal">&gt;</code>),
  18. and hash indexes only support equality queries.
  19. </p><p>
  20. So if you index, say, an image collection with a
  21. <span class="productname">PostgreSQL</span> B-tree, you can only issue queries
  22. such as <span class="quote">“<span class="quote">is imagex equal to imagey</span>”</span>, <span class="quote">“<span class="quote">is imagex less
  23. than imagey</span>”</span> and <span class="quote">“<span class="quote">is imagex greater than imagey</span>”</span>.
  24. Depending on how you define <span class="quote">“<span class="quote">equals</span>”</span>, <span class="quote">“<span class="quote">less than</span>”</span>
  25. and <span class="quote">“<span class="quote">greater than</span>”</span> in this context, this could be useful.
  26. However, by using a <acronym class="acronym">GiST</acronym> based index, you could create
  27. ways to ask domain-specific questions, perhaps <span class="quote">“<span class="quote">find all images of
  28. horses</span>”</span> or <span class="quote">“<span class="quote">find all over-exposed images</span>”</span>.
  29. </p><p>
  30. All it takes to get a <acronym class="acronym">GiST</acronym> access method up and running
  31. is to implement several user-defined methods, which define the behavior of
  32. keys in the tree. Of course these methods have to be pretty fancy to
  33. support fancy queries, but for all the standard queries (B-trees,
  34. R-trees, etc.) they're relatively straightforward. In short,
  35. <acronym class="acronym">GiST</acronym> combines extensibility along with generality, code
  36. reuse, and a clean interface.
  37. </p><p>
  38. There are five methods that an index operator class for
  39. <acronym class="acronym">GiST</acronym> must provide, and four that are optional.
  40. Correctness of the index is ensured
  41. by proper implementation of the <code class="function">same</code>, <code class="function">consistent</code>
  42. and <code class="function">union</code> methods, while efficiency (size and speed) of the
  43. index will depend on the <code class="function">penalty</code> and <code class="function">picksplit</code>
  44. methods.
  45. Two optional methods are <code class="function">compress</code> and
  46. <code class="function">decompress</code>, which allow an index to have internal tree data of
  47. a different type than the data it indexes. The leaves are to be of the
  48. indexed data type, while the other tree nodes can be of any C struct (but
  49. you still have to follow <span class="productname">PostgreSQL</span> data type rules here,
  50. see about <code class="literal">varlena</code> for variable sized data). If the tree's
  51. internal data type exists at the SQL level, the <code class="literal">STORAGE</code> option
  52. of the <code class="command">CREATE OPERATOR CLASS</code> command can be used.
  53. The optional eighth method is <code class="function">distance</code>, which is needed
  54. if the operator class wishes to support ordered scans (nearest-neighbor
  55. searches). The optional ninth method <code class="function">fetch</code> is needed if the
  56. operator class wishes to support index-only scans, except when the
  57. <code class="function">compress</code> method is omitted.
  58. </p><div class="variablelist"><dl class="variablelist"><dt><span class="term"><code class="function">consistent</code></span></dt><dd><p>
  59. Given an index entry <code class="literal">p</code> and a query value <code class="literal">q</code>,
  60. this function determines whether the index entry is
  61. <span class="quote">“<span class="quote">consistent</span>”</span> with the query; that is, could the predicate
  62. <span class="quote">“<span class="quote"><em class="replaceable"><code>indexed_column</code></em>
  63. <em class="replaceable"><code>indexable_operator</code></em> <code class="literal">q</code></span>”</span> be true for
  64. any row represented by the index entry? For a leaf index entry this is
  65. equivalent to testing the indexable condition, while for an internal
  66. tree node this determines whether it is necessary to scan the subtree
  67. of the index represented by the tree node. When the result is
  68. <code class="literal">true</code>, a <code class="literal">recheck</code> flag must also be returned.
  69. This indicates whether the predicate is certainly true or only possibly
  70. true. If <code class="literal">recheck</code> = <code class="literal">false</code> then the index has
  71. tested the predicate condition exactly, whereas if <code class="literal">recheck</code>
  72. = <code class="literal">true</code> the row is only a candidate match. In that case the
  73. system will automatically evaluate the
  74. <em class="replaceable"><code>indexable_operator</code></em> against the actual row value to see
  75. if it is really a match. This convention allows
  76. <acronym class="acronym">GiST</acronym> to support both lossless and lossy index
  77. structures.
  78. </p><p>
  79. The <acronym class="acronym">SQL</acronym> declaration of the function must look like this:
  80. </p><pre class="programlisting">
  81. CREATE OR REPLACE FUNCTION my_consistent(internal, data_type, smallint, oid, internal)
  82. RETURNS bool
  83. AS 'MODULE_PATHNAME'
  84. LANGUAGE C STRICT;
  85. </pre><p>
  86. And the matching code in the C module could then follow this skeleton:
  87. </p><pre class="programlisting">
  88. PG_FUNCTION_INFO_V1(my_consistent);
  89. Datum
  90. my_consistent(PG_FUNCTION_ARGS)
  91. {
  92. GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
  93. data_type *query = PG_GETARG_DATA_TYPE_P(1);
  94. StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
  95. /* Oid subtype = PG_GETARG_OID(3); */
  96. bool *recheck = (bool *) PG_GETARG_POINTER(4);
  97. data_type *key = DatumGetDataType(entry-&gt;key);
  98. bool retval;
  99. /*
  100. * determine return value as a function of strategy, key and query.
  101. *
  102. * Use GIST_LEAF(entry) to know where you're called in the index tree,
  103. * which comes handy when supporting the = operator for example (you could
  104. * check for non empty union() in non-leaf nodes and equality in leaf
  105. * nodes).
  106. */
  107. *recheck = true; /* or false if check is exact */
  108. PG_RETURN_BOOL(retval);
  109. }
  110. </pre><p>
  111. Here, <code class="varname">key</code> is an element in the index and <code class="varname">query</code>
  112. the value being looked up in the index. The <code class="literal">StrategyNumber</code>
  113. parameter indicates which operator of your operator class is being
  114. applied — it matches one of the operator numbers in the
  115. <code class="command">CREATE OPERATOR CLASS</code> command.
  116. </p><p>
  117. Depending on which operators you have included in the class, the data
  118. type of <code class="varname">query</code> could vary with the operator, since it will
  119. be whatever type is on the righthand side of the operator, which might
  120. be different from the indexed data type appearing on the lefthand side.
  121. (The above code skeleton assumes that only one type is possible; if
  122. not, fetching the <code class="varname">query</code> argument value would have to depend
  123. on the operator.) It is recommended that the SQL declaration of
  124. the <code class="function">consistent</code> function use the opclass's indexed data
  125. type for the <code class="varname">query</code> argument, even though the actual type
  126. might be something else depending on the operator.
  127. </p></dd><dt><span class="term"><code class="function">union</code></span></dt><dd><p>
  128. This method consolidates information in the tree. Given a set of
  129. entries, this function generates a new index entry that represents
  130. all the given entries.
  131. </p><p>
  132. The <acronym class="acronym">SQL</acronym> declaration of the function must look like this:
  133. </p><pre class="programlisting">
  134. CREATE OR REPLACE FUNCTION my_union(internal, internal)
  135. RETURNS storage_type
  136. AS 'MODULE_PATHNAME'
  137. LANGUAGE C STRICT;
  138. </pre><p>
  139. And the matching code in the C module could then follow this skeleton:
  140. </p><pre class="programlisting">
  141. PG_FUNCTION_INFO_V1(my_union);
  142. Datum
  143. my_union(PG_FUNCTION_ARGS)
  144. {
  145. GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
  146. GISTENTRY *ent = entryvec-&gt;vector;
  147. data_type *out,
  148. *tmp,
  149. *old;
  150. int numranges,
  151. i = 0;
  152. numranges = entryvec-&gt;n;
  153. tmp = DatumGetDataType(ent[0].key);
  154. out = tmp;
  155. if (numranges == 1)
  156. {
  157. out = data_type_deep_copy(tmp);
  158. PG_RETURN_DATA_TYPE_P(out);
  159. }
  160. for (i = 1; i &lt; numranges; i++)
  161. {
  162. old = out;
  163. tmp = DatumGetDataType(ent[i].key);
  164. out = my_union_implementation(out, tmp);
  165. }
  166. PG_RETURN_DATA_TYPE_P(out);
  167. }
  168. </pre><p>
  169. </p><p>
  170. As you can see, in this skeleton we're dealing with a data type
  171. where <code class="literal">union(X, Y, Z) = union(union(X, Y), Z)</code>. It's easy
  172. enough to support data types where this is not the case, by
  173. implementing the proper union algorithm in this
  174. <acronym class="acronym">GiST</acronym> support method.
  175. </p><p>
  176. The result of the <code class="function">union</code> function must be a value of the
  177. index's storage type, whatever that is (it might or might not be
  178. different from the indexed column's type). The <code class="function">union</code>
  179. function should return a pointer to newly <code class="function">palloc()</code>ed
  180. memory. You can't just return the input value as-is, even if there is
  181. no type change.
  182. </p><p>
  183. As shown above, the <code class="function">union</code> function's
  184. first <code class="type">internal</code> argument is actually
  185. a <code class="structname">GistEntryVector</code> pointer. The second argument is a
  186. pointer to an integer variable, which can be ignored. (It used to be
  187. required that the <code class="function">union</code> function store the size of its
  188. result value into that variable, but this is no longer necessary.)
  189. </p></dd><dt><span class="term"><code class="function">compress</code></span></dt><dd><p>
  190. Converts a data item into a format suitable for physical storage in
  191. an index page.
  192. If the <code class="function">compress</code> method is omitted, data items are stored
  193. in the index without modification.
  194. </p><p>
  195. The <acronym class="acronym">SQL</acronym> declaration of the function must look like this:
  196. </p><pre class="programlisting">
  197. CREATE OR REPLACE FUNCTION my_compress(internal)
  198. RETURNS internal
  199. AS 'MODULE_PATHNAME'
  200. LANGUAGE C STRICT;
  201. </pre><p>
  202. And the matching code in the C module could then follow this skeleton:
  203. </p><pre class="programlisting">
  204. PG_FUNCTION_INFO_V1(my_compress);
  205. Datum
  206. my_compress(PG_FUNCTION_ARGS)
  207. {
  208. GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
  209. GISTENTRY *retval;
  210. if (entry-&gt;leafkey)
  211. {
  212. /* replace entry-&gt;key with a compressed version */
  213. compressed_data_type *compressed_data = palloc(sizeof(compressed_data_type));
  214. /* fill *compressed_data from entry-&gt;key ... */
  215. retval = palloc(sizeof(GISTENTRY));
  216. gistentryinit(*retval, PointerGetDatum(compressed_data),
  217. entry-&gt;rel, entry-&gt;page, entry-&gt;offset, FALSE);
  218. }
  219. else
  220. {
  221. /* typically we needn't do anything with non-leaf entries */
  222. retval = entry;
  223. }
  224. PG_RETURN_POINTER(retval);
  225. }
  226. </pre><p>
  227. </p><p>
  228. You have to adapt <em class="replaceable"><code>compressed_data_type</code></em> to the specific
  229. type you're converting to in order to compress your leaf nodes, of
  230. course.
  231. </p></dd><dt><span class="term"><code class="function">decompress</code></span></dt><dd><p>
  232. Converts the stored representation of a data item into a format that
  233. can be manipulated by the other GiST methods in the operator class.
  234. If the <code class="function">decompress</code> method is omitted, it is assumed that
  235. the other GiST methods can work directly on the stored data format.
  236. (<code class="function">decompress</code> is not necessarily the reverse of
  237. the <code class="function">compress</code> method; in particular,
  238. if <code class="function">compress</code> is lossy then it's impossible
  239. for <code class="function">decompress</code> to exactly reconstruct the original
  240. data. <code class="function">decompress</code> is not necessarily equivalent
  241. to <code class="function">fetch</code>, either, since the other GiST methods might not
  242. require full reconstruction of the data.)
  243. </p><p>
  244. The <acronym class="acronym">SQL</acronym> declaration of the function must look like this:
  245. </p><pre class="programlisting">
  246. CREATE OR REPLACE FUNCTION my_decompress(internal)
  247. RETURNS internal
  248. AS 'MODULE_PATHNAME'
  249. LANGUAGE C STRICT;
  250. </pre><p>
  251. And the matching code in the C module could then follow this skeleton:
  252. </p><pre class="programlisting">
  253. PG_FUNCTION_INFO_V1(my_decompress);
  254. Datum
  255. my_decompress(PG_FUNCTION_ARGS)
  256. {
  257. PG_RETURN_POINTER(PG_GETARG_POINTER(0));
  258. }
  259. </pre><p>
  260. The above skeleton is suitable for the case where no decompression
  261. is needed. (But, of course, omitting the method altogether is even
  262. easier, and is recommended in such cases.)
  263. </p></dd><dt><span class="term"><code class="function">penalty</code></span></dt><dd><p>
  264. Returns a value indicating the <span class="quote">“<span class="quote">cost</span>”</span> of inserting the new
  265. entry into a particular branch of the tree. Items will be inserted
  266. down the path of least <code class="function">penalty</code> in the tree.
  267. Values returned by <code class="function">penalty</code> should be non-negative.
  268. If a negative value is returned, it will be treated as zero.
  269. </p><p>
  270. The <acronym class="acronym">SQL</acronym> declaration of the function must look like this:
  271. </p><pre class="programlisting">
  272. CREATE OR REPLACE FUNCTION my_penalty(internal, internal, internal)
  273. RETURNS internal
  274. AS 'MODULE_PATHNAME'
  275. LANGUAGE C STRICT; -- in some cases penalty functions need not be strict
  276. </pre><p>
  277. And the matching code in the C module could then follow this skeleton:
  278. </p><pre class="programlisting">
  279. PG_FUNCTION_INFO_V1(my_penalty);
  280. Datum
  281. my_penalty(PG_FUNCTION_ARGS)
  282. {
  283. GISTENTRY *origentry = (GISTENTRY *) PG_GETARG_POINTER(0);
  284. GISTENTRY *newentry = (GISTENTRY *) PG_GETARG_POINTER(1);
  285. float *penalty = (float *) PG_GETARG_POINTER(2);
  286. data_type *orig = DatumGetDataType(origentry-&gt;key);
  287. data_type *new = DatumGetDataType(newentry-&gt;key);
  288. *penalty = my_penalty_implementation(orig, new);
  289. PG_RETURN_POINTER(penalty);
  290. }
  291. </pre><p>
  292. For historical reasons, the <code class="function">penalty</code> function doesn't
  293. just return a <code class="type">float</code> result; instead it has to store the value
  294. at the location indicated by the third argument. The return
  295. value per se is ignored, though it's conventional to pass back the
  296. address of that argument.
  297. </p><p>
  298. The <code class="function">penalty</code> function is crucial to good performance of
  299. the index. It'll get used at insertion time to determine which branch
  300. to follow when choosing where to add the new entry in the tree. At
  301. query time, the more balanced the index, the quicker the lookup.
  302. </p></dd><dt><span class="term"><code class="function">picksplit</code></span></dt><dd><p>
  303. When an index page split is necessary, this function decides which
  304. entries on the page are to stay on the old page, and which are to move
  305. to the new page.
  306. </p><p>
  307. The <acronym class="acronym">SQL</acronym> declaration of the function must look like this:
  308. </p><pre class="programlisting">
  309. CREATE OR REPLACE FUNCTION my_picksplit(internal, internal)
  310. RETURNS internal
  311. AS 'MODULE_PATHNAME'
  312. LANGUAGE C STRICT;
  313. </pre><p>
  314. And the matching code in the C module could then follow this skeleton:
  315. </p><pre class="programlisting">
  316. PG_FUNCTION_INFO_V1(my_picksplit);
  317. Datum
  318. my_picksplit(PG_FUNCTION_ARGS)
  319. {
  320. GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
  321. GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
  322. OffsetNumber maxoff = entryvec-&gt;n - 1;
  323. GISTENTRY *ent = entryvec-&gt;vector;
  324. int i,
  325. nbytes;
  326. OffsetNumber *left,
  327. *right;
  328. data_type *tmp_union;
  329. data_type *unionL;
  330. data_type *unionR;
  331. GISTENTRY **raw_entryvec;
  332. maxoff = entryvec-&gt;n - 1;
  333. nbytes = (maxoff + 1) * sizeof(OffsetNumber);
  334. v-&gt;spl_left = (OffsetNumber *) palloc(nbytes);
  335. left = v-&gt;spl_left;
  336. v-&gt;spl_nleft = 0;
  337. v-&gt;spl_right = (OffsetNumber *) palloc(nbytes);
  338. right = v-&gt;spl_right;
  339. v-&gt;spl_nright = 0;
  340. unionL = NULL;
  341. unionR = NULL;
  342. /* Initialize the raw entry vector. */
  343. raw_entryvec = (GISTENTRY **) malloc(entryvec-&gt;n * sizeof(void *));
  344. for (i = FirstOffsetNumber; i &lt;= maxoff; i = OffsetNumberNext(i))
  345. raw_entryvec[i] = &amp;(entryvec-&gt;vector[i]);
  346. for (i = FirstOffsetNumber; i &lt;= maxoff; i = OffsetNumberNext(i))
  347. {
  348. int real_index = raw_entryvec[i] - entryvec-&gt;vector;
  349. tmp_union = DatumGetDataType(entryvec-&gt;vector[real_index].key);
  350. Assert(tmp_union != NULL);
  351. /*
  352. * Choose where to put the index entries and update unionL and unionR
  353. * accordingly. Append the entries to either v-&gt;spl_left or
  354. * v-&gt;spl_right, and care about the counters.
  355. */
  356. if (my_choice_is_left(unionL, curl, unionR, curr))
  357. {
  358. if (unionL == NULL)
  359. unionL = tmp_union;
  360. else
  361. unionL = my_union_implementation(unionL, tmp_union);
  362. *left = real_index;
  363. ++left;
  364. ++(v-&gt;spl_nleft);
  365. }
  366. else
  367. {
  368. /*
  369. * Same on the right
  370. */
  371. }
  372. }
  373. v-&gt;spl_ldatum = DataTypeGetDatum(unionL);
  374. v-&gt;spl_rdatum = DataTypeGetDatum(unionR);
  375. PG_RETURN_POINTER(v);
  376. }
  377. </pre><p>
  378. Notice that the <code class="function">picksplit</code> function's result is delivered
  379. by modifying the passed-in <code class="structname">v</code> structure. The return
  380. value per se is ignored, though it's conventional to pass back the
  381. address of <code class="structname">v</code>.
  382. </p><p>
  383. Like <code class="function">penalty</code>, the <code class="function">picksplit</code> function
  384. is crucial to good performance of the index. Designing suitable
  385. <code class="function">penalty</code> and <code class="function">picksplit</code> implementations
  386. is where the challenge of implementing well-performing
  387. <acronym class="acronym">GiST</acronym> indexes lies.
  388. </p></dd><dt><span class="term"><code class="function">same</code></span></dt><dd><p>
  389. Returns true if two index entries are identical, false otherwise.
  390. (An <span class="quote">“<span class="quote">index entry</span>”</span> is a value of the index's storage type,
  391. not necessarily the original indexed column's type.)
  392. </p><p>
  393. The <acronym class="acronym">SQL</acronym> declaration of the function must look like this:
  394. </p><pre class="programlisting">
  395. CREATE OR REPLACE FUNCTION my_same(storage_type, storage_type, internal)
  396. RETURNS internal
  397. AS 'MODULE_PATHNAME'
  398. LANGUAGE C STRICT;
  399. </pre><p>
  400. And the matching code in the C module could then follow this skeleton:
  401. </p><pre class="programlisting">
  402. PG_FUNCTION_INFO_V1(my_same);
  403. Datum
  404. my_same(PG_FUNCTION_ARGS)
  405. {
  406. prefix_range *v1 = PG_GETARG_PREFIX_RANGE_P(0);
  407. prefix_range *v2 = PG_GETARG_PREFIX_RANGE_P(1);
  408. bool *result = (bool *) PG_GETARG_POINTER(2);
  409. *result = my_eq(v1, v2);
  410. PG_RETURN_POINTER(result);
  411. }
  412. </pre><p>
  413. For historical reasons, the <code class="function">same</code> function doesn't
  414. just return a Boolean result; instead it has to store the flag
  415. at the location indicated by the third argument. The return
  416. value per se is ignored, though it's conventional to pass back the
  417. address of that argument.
  418. </p></dd><dt><span class="term"><code class="function">distance</code></span></dt><dd><p>
  419. Given an index entry <code class="literal">p</code> and a query value <code class="literal">q</code>,
  420. this function determines the index entry's
  421. <span class="quote">“<span class="quote">distance</span>”</span> from the query value. This function must be
  422. supplied if the operator class contains any ordering operators.
  423. A query using the ordering operator will be implemented by returning
  424. index entries with the smallest <span class="quote">“<span class="quote">distance</span>”</span> values first,
  425. so the results must be consistent with the operator's semantics.
  426. For a leaf index entry the result just represents the distance to
  427. the index entry; for an internal tree node, the result must be the
  428. smallest distance that any child entry could have.
  429. </p><p>
  430. The <acronym class="acronym">SQL</acronym> declaration of the function must look like this:
  431. </p><pre class="programlisting">
  432. CREATE OR REPLACE FUNCTION my_distance(internal, data_type, smallint, oid, internal)
  433. RETURNS float8
  434. AS 'MODULE_PATHNAME'
  435. LANGUAGE C STRICT;
  436. </pre><p>
  437. And the matching code in the C module could then follow this skeleton:
  438. </p><pre class="programlisting">
  439. PG_FUNCTION_INFO_V1(my_distance);
  440. Datum
  441. my_distance(PG_FUNCTION_ARGS)
  442. {
  443. GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
  444. data_type *query = PG_GETARG_DATA_TYPE_P(1);
  445. StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
  446. /* Oid subtype = PG_GETARG_OID(3); */
  447. /* bool *recheck = (bool *) PG_GETARG_POINTER(4); */
  448. data_type *key = DatumGetDataType(entry-&gt;key);
  449. double retval;
  450. /*
  451. * determine return value as a function of strategy, key and query.
  452. */
  453. PG_RETURN_FLOAT8(retval);
  454. }
  455. </pre><p>
  456. The arguments to the <code class="function">distance</code> function are identical to
  457. the arguments of the <code class="function">consistent</code> function.
  458. </p><p>
  459. Some approximation is allowed when determining the distance, so long
  460. as the result is never greater than the entry's actual distance. Thus,
  461. for example, distance to a bounding box is usually sufficient in
  462. geometric applications. For an internal tree node, the distance
  463. returned must not be greater than the distance to any of the child
  464. nodes. If the returned distance is not exact, the function must set
  465. <code class="literal">*recheck</code> to true. (This is not necessary for internal tree
  466. nodes; for them, the calculation is always assumed to be inexact.) In
  467. this case the executor will calculate the accurate distance after
  468. fetching the tuple from the heap, and reorder the tuples if necessary.
  469. </p><p>
  470. If the distance function returns <code class="literal">*recheck = true</code> for any
  471. leaf node, the original ordering operator's return type must
  472. be <code class="type">float8</code> or <code class="type">float4</code>, and the distance function's
  473. result values must be comparable to those of the original ordering
  474. operator, since the executor will sort using both distance function
  475. results and recalculated ordering-operator results. Otherwise, the
  476. distance function's result values can be any finite <code class="type">float8</code>
  477. values, so long as the relative order of the result values matches the
  478. order returned by the ordering operator. (Infinity and minus infinity
  479. are used internally to handle cases such as nulls, so it is not
  480. recommended that <code class="function">distance</code> functions return these values.)
  481. </p></dd><dt><span class="term"><code class="function">fetch</code></span></dt><dd><p>
  482. Converts the compressed index representation of a data item into the
  483. original data type, for index-only scans. The returned data must be an
  484. exact, non-lossy copy of the originally indexed value.
  485. </p><p>
  486. The <acronym class="acronym">SQL</acronym> declaration of the function must look like this:
  487. </p><pre class="programlisting">
  488. CREATE OR REPLACE FUNCTION my_fetch(internal)
  489. RETURNS internal
  490. AS 'MODULE_PATHNAME'
  491. LANGUAGE C STRICT;
  492. </pre><p>
  493. The argument is a pointer to a <code class="structname">GISTENTRY</code> struct. On
  494. entry, its <code class="structfield">key</code> field contains a non-NULL leaf datum in
  495. compressed form. The return value is another <code class="structname">GISTENTRY</code>
  496. struct, whose <code class="structfield">key</code> field contains the same datum in its
  497. original, uncompressed form. If the opclass's compress function does
  498. nothing for leaf entries, the <code class="function">fetch</code> method can return the
  499. argument as-is. Or, if the opclass does not have a compress function,
  500. the <code class="function">fetch</code> method can be omitted as well, since it would
  501. necessarily be a no-op.
  502. </p><p>
  503. The matching code in the C module could then follow this skeleton:
  504. </p><pre class="programlisting">
  505. PG_FUNCTION_INFO_V1(my_fetch);
  506. Datum
  507. my_fetch(PG_FUNCTION_ARGS)
  508. {
  509. GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
  510. input_data_type *in = DatumGetPointer(entry-&gt;key);
  511. fetched_data_type *fetched_data;
  512. GISTENTRY *retval;
  513. retval = palloc(sizeof(GISTENTRY));
  514. fetched_data = palloc(sizeof(fetched_data_type));
  515. /*
  516. * Convert 'fetched_data' into the a Datum of the original datatype.
  517. */
  518. /* fill *retval from fetched_data. */
  519. gistentryinit(*retval, PointerGetDatum(converted_datum),
  520. entry-&gt;rel, entry-&gt;page, entry-&gt;offset, FALSE);
  521. PG_RETURN_POINTER(retval);
  522. }
  523. </pre><p>
  524. </p><p>
  525. If the compress method is lossy for leaf entries, the operator class
  526. cannot support index-only scans, and must not define
  527. a <code class="function">fetch</code> function.
  528. </p></dd></dl></div><p>
  529. All the GiST support methods are normally called in short-lived memory
  530. contexts; that is, <code class="varname">CurrentMemoryContext</code> will get reset after
  531. each tuple is processed. It is therefore not very important to worry about
  532. pfree'ing everything you palloc. However, in some cases it's useful for a
  533. support method to cache data across repeated calls. To do that, allocate
  534. the longer-lived data in <code class="literal">fcinfo-&gt;flinfo-&gt;fn_mcxt</code>, and
  535. keep a pointer to it in <code class="literal">fcinfo-&gt;flinfo-&gt;fn_extra</code>. Such
  536. data will survive for the life of the index operation (e.g., a single GiST
  537. index scan, index build, or index tuple insertion). Be careful to pfree
  538. the previous value when replacing a <code class="literal">fn_extra</code> value, or the leak
  539. will accumulate for the duration of the operation.
  540. </p></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="gist-builtin-opclasses.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="gist.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="gist-implementation.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">64.2. Built-in Operator Classes </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 64.4. Implementation</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1