@@ -1680,6 +1680,15 @@ typedef struct
1680
1680
itself.
1681
1681
</para>
1682
1682
1683
+ <para>
1684
+ Another important point is to avoid leaving any uninitialized bits
1685
+ within data type values; for example, take care to zero out any
1686
+ alignment padding bytes that might be present in structs. Without
1687
+ this, logically-equivalent constants of your data type might be
1688
+ seen as unequal by the planner, leading to inefficient (though not
1689
+ incorrect) plans.
1690
+ </para>
1691
+
1683
1692
<warning>
1684
1693
<para>
1685
1694
<emphasis>Never</> modify the contents of a pass-by-reference input
@@ -1723,7 +1732,7 @@ typedef struct {
1723
1732
char buffer[40]; /* our source data */
1724
1733
...
1725
1734
text *destination = (text *) palloc(VARHDRSZ + 40);
1726
- destination->length = VARHDRSZ + 40;
1735
+ SET_VARSIZE( destination, VARHDRSZ + 40) ;
1727
1736
memcpy(destination->data, buffer, 40);
1728
1737
...
1729
1738
]]>
@@ -1732,6 +1741,8 @@ memcpy(destination->data, buffer, 40);
1732
1741
<literal>VARHDRSZ</> is the same as <literal>sizeof(int4)</>, but
1733
1742
it's considered good style to use the macro <literal>VARHDRSZ</>
1734
1743
to refer to the size of the overhead for a variable-length type.
1744
+ Also, the length field <emphasis>must</> be set using the
1745
+ <literal>SET_VARSIZE</> macro, not by simple assignment.
1735
1746
</para>
1736
1747
1737
1748
<para>
@@ -2345,13 +2356,16 @@ concat_text(PG_FUNCTION_ARGS)
2345
2356
2346
2357
<listitem>
2347
2358
<para>
2348
- Always zero the bytes of your structures using
2349
- <function>memset</function>. Without this, it's difficult to
2359
+ Always zero the bytes of your structures using <function>memset</>
2360
+ (or allocate them with <function>palloc0</> in the first place).
2361
+ Even if you assign to each field of your structure, there might be
2362
+ alignment padding (holes in the structure) that contain
2363
+ garbage values. Without this, it's difficult to
2350
2364
support hash indexes or hash joins, as you must pick out only
2351
2365
the significant bits of your data structure to compute a hash.
2352
- Even if you initialize all fields of your structure, there might be
2353
- alignment padding (holes in the structure) that contain
2354
- garbage values.
2366
+ The planner also sometimes relies on comparing constants via
2367
+ bitwise equality, so you can get undesirable planning results if
2368
+ logically-equivalent values aren't bitwise equal .
2355
2369
</para>
2356
2370
</listitem>
2357
2371
0 commit comments