@@ -1741,6 +1741,15 @@ typedef struct
1741
1741
itself.
1742
1742
</para>
1743
1743
1744
+ <para>
1745
+ Another important point is to avoid leaving any uninitialized bits
1746
+ within data type values; for example, take care to zero out any
1747
+ alignment padding bytes that might be present in structs. Without
1748
+ this, logically-equivalent constants of your data type might be
1749
+ seen as unequal by the planner, leading to inefficient (though not
1750
+ incorrect) plans.
1751
+ </para>
1752
+
1744
1753
<warning>
1745
1754
<para>
1746
1755
<emphasis>Never</> modify the contents of a pass-by-reference input
@@ -1784,7 +1793,7 @@ typedef struct {
1784
1793
char buffer[40]; /* our source data */
1785
1794
...
1786
1795
text *destination = (text *) palloc(VARHDRSZ + 40);
1787
- destination->length = VARHDRSZ + 40;
1796
+ SET_VARSIZE( destination, VARHDRSZ + 40) ;
1788
1797
memcpy(destination->data, buffer, 40);
1789
1798
...
1790
1799
]]>
@@ -1793,6 +1802,8 @@ memcpy(destination->data, buffer, 40);
1793
1802
<literal>VARHDRSZ</> is the same as <literal>sizeof(int4)</>, but
1794
1803
it's considered good style to use the macro <literal>VARHDRSZ</>
1795
1804
to refer to the size of the overhead for a variable-length type.
1805
+ Also, the length field <emphasis>must</> be set using the
1806
+ <literal>SET_VARSIZE</> macro, not by simple assignment.
1796
1807
</para>
1797
1808
1798
1809
<para>
@@ -2406,13 +2417,16 @@ concat_text(PG_FUNCTION_ARGS)
2406
2417
2407
2418
<listitem>
2408
2419
<para>
2409
- Always zero the bytes of your structures using
2410
- <function>memset</function>. Without this, it's difficult to
2420
+ Always zero the bytes of your structures using <function>memset</>
2421
+ (or allocate them with <function>palloc0</> in the first place).
2422
+ Even if you assign to each field of your structure, there might be
2423
+ alignment padding (holes in the structure) that contain
2424
+ garbage values. Without this, it's difficult to
2411
2425
support hash indexes or hash joins, as you must pick out only
2412
2426
the significant bits of your data structure to compute a hash.
2413
- Even if you initialize all fields of your structure, there might be
2414
- alignment padding (holes in the structure) that contain
2415
- garbage values.
2427
+ The planner also sometimes relies on comparing constants via
2428
+ bitwise equality, so you can get undesirable planning results if
2429
+ logically-equivalent values aren't bitwise equal .
2416
2430
</para>
2417
2431
</listitem>
2418
2432
0 commit comments