1 <!-- doc/src/sgml/sources.sgml -->
4 <title>PostgreSQL Coding Conventions
</title>
6 <sect1 id=
"source-format">
7 <title>Formatting
</title>
10 Source code formatting uses
4 column tab spacing, with
11 tabs preserved (i.e., tabs are not expanded to spaces).
12 Each logical indentation level is one additional tab stop.
16 Layout rules (brace positioning, etc.) follow BSD conventions. In
17 particular, curly braces for the controlled blocks of
<literal>if
</literal>,
18 <literal>while
</literal>,
<literal>switch
</literal>, etc. go on their own lines.
22 Limit line lengths so that the code is readable in an
80-column window.
23 (This doesn't mean that you must never go past
80 columns. For instance,
24 breaking a long error message string in arbitrary places just to keep the
25 code within
80 columns is probably not a net gain in readability.)
29 To maintain a consistent coding style, do not use C++ style comments
30 (
<literal>//
</literal> comments).
<application>pgindent
</application>
31 will replace them with
<literal>/* ... */
</literal>.
35 The preferred style for multi-line comment blocks is
38 * comment text begins here
42 Note that comment blocks that begin in column
1 will be preserved as-is
43 by
<application>pgindent
</application>, but it will re-flow indented comment blocks
44 as though they were plain text. If you want to preserve the line breaks
45 in an indented block, add dashes like this:
48 * comment text begins here
56 While submitted patches do not absolutely have to follow these formatting
57 rules, it's a good idea to do so. Your code will get run through
58 <application>pgindent
</application> before the next release, so there's no point in
59 making it look nice under some other set of formatting conventions.
60 A good rule of thumb for patches is
<quote>make the new code look like
61 the existing code around it
</quote>.
65 The
<filename>src/tools/editors
</filename> directory contains sample settings
66 files that can be used with the
<productname>Emacs
</productname>,
67 <productname>xemacs
</productname> or
<productname>vim
</productname>
68 editors to help ensure that they format code according to these
73 If you'd like to run
<application>pgindent
</application> locally
74 to help make your code match project style, see
75 the
<filename>src/tools/pgindent
</filename> directory.
79 The text browsing tools
<application>more
</application> and
80 <application>less
</application> can be invoked as:
85 to make them show tabs appropriately.
89 <sect1 id=
"error-message-reporting">
90 <title>Reporting Errors Within the Server
</title>
93 <primary>ereport
</primary>
96 <primary>elog
</primary>
100 Error, warning, and log messages generated within the server code
101 should be created using
<function>ereport
</function>, or its older cousin
102 <function>elog
</function>. The use of this function is complex enough to
103 require some explanation.
107 There are two required elements for every message: a severity level
108 (ranging from
<literal>DEBUG
</literal> to
<literal>PANIC
</literal>, defined
109 in
<filename>src/include/utils/elog.h
</filename>) and a primary
110 message text. In addition there are optional elements, the most
111 common of which is an error identifier code that follows the SQL spec's
112 SQLSTATE conventions.
113 <function>ereport
</function> itself is just a shell macro that exists
114 mainly for the syntactic convenience of making message generation
115 look like a single function call in the C source code. The only parameter
116 accepted directly by
<function>ereport
</function> is the severity level.
117 The primary message text and any optional message elements are
118 generated by calling auxiliary functions, such as
<function>errmsg
</function>,
119 within the
<function>ereport
</function> call.
123 A typical call to
<function>ereport
</function> might look like this:
126 errcode(ERRCODE_DIVISION_BY_ZERO),
127 errmsg(
"division by zero"));
129 This specifies error severity level
<literal>ERROR
</literal> (a run-of-the-mill
130 error). The
<function>errcode
</function> call specifies the SQLSTATE error code
131 using a macro defined in
<filename>src/include/utils/errcodes.h
</filename>. The
132 <function>errmsg
</function> call provides the primary message text.
136 You will also frequently see this older style, with an extra set of
137 parentheses surrounding the auxiliary function calls:
140 (errcode(ERRCODE_DIVISION_BY_ZERO),
141 errmsg(
"division by zero")));
143 The extra parentheses were required
144 before
<productname>PostgreSQL
</productname> version
12, but are now
149 Here is a more complex example:
152 errcode(ERRCODE_AMBIGUOUS_FUNCTION),
153 errmsg(
"function %s is not unique",
154 func_signature_string(funcname, nargs,
155 NIL, actual_arg_types)),
156 errhint(
"Unable to choose a best candidate function. "
157 "You might need to add explicit typecasts."));
159 This illustrates the use of format codes to embed run-time values into
160 a message text. Also, an optional
<quote>hint
</quote> message is provided.
161 The auxiliary function calls can be written in any order, but
162 conventionally
<function>errcode
</function>
163 and
<function>errmsg
</function> appear first.
167 If the severity level is
<literal>ERROR
</literal> or higher,
168 <function>ereport
</function> aborts execution of the current query
169 and does not return to the caller. If the severity level is
170 lower than
<literal>ERROR
</literal>,
<function>ereport
</function> returns normally.
174 The available auxiliary routines for
<function>ereport
</function> are:
178 <function>errcode(sqlerrcode)
</function> specifies the SQLSTATE error identifier
179 code for the condition. If this routine is not called, the error
180 identifier defaults to
181 <literal>ERRCODE_INTERNAL_ERROR
</literal> when the error severity level is
182 <literal>ERROR
</literal> or higher,
<literal>ERRCODE_WARNING
</literal> when the
183 error level is
<literal>WARNING
</literal>, otherwise (for
<literal>NOTICE
</literal>
184 and below)
<literal>ERRCODE_SUCCESSFUL_COMPLETION
</literal>.
185 While these defaults are often convenient, always think whether they
186 are appropriate before omitting the
<function>errcode()
</function> call.
191 <function>errmsg(const char *msg, ...)
</function> specifies the primary error
192 message text, and possibly run-time values to insert into it. Insertions
193 are specified by
<function>sprintf
</function>-style format codes. In addition to
194 the standard format codes accepted by
<function>sprintf
</function>, the format
195 code
<literal>%m
</literal> can be used to insert the error message returned
196 by
<function>strerror
</function> for the current value of
<literal>errno
</literal>.
199 That is, the value that was current when the
<function>ereport
</function> call
200 was reached; changes of
<literal>errno
</literal> within the auxiliary reporting
201 routines will not affect it. That would not be true if you were to
202 write
<literal>strerror(errno)
</literal> explicitly in
<function>errmsg
</function>'s
203 parameter list; accordingly, do not do so.
206 <literal>%m
</literal> does not require any
207 corresponding entry in the parameter list for
<function>errmsg
</function>.
208 Note that the message string will be run through
<function>gettext
</function>
209 for possible localization before format codes are processed.
214 <function>errmsg_internal(const char *msg, ...)
</function> is the same as
215 <function>errmsg
</function>, except that the message string will not be
216 translated nor included in the internationalization message dictionary.
217 This should be used for
<quote>cannot happen
</quote> cases that are probably
218 not worth expending translation effort on.
223 <function>errmsg_plural(const char *fmt_singular, const char *fmt_plural,
224 unsigned long n, ...)
</function> is like
<function>errmsg
</function>, but with
225 support for various plural forms of the message.
226 <replaceable>fmt_singular
</replaceable> is the English singular format,
227 <replaceable>fmt_plural
</replaceable> is the English plural format,
228 <replaceable>n
</replaceable> is the integer value that determines which plural
229 form is needed, and the remaining arguments are formatted according
230 to the selected format string. For more information see
231 <xref linkend=
"nls-guidelines"/>.
236 <function>errdetail(const char *msg, ...)
</function> supplies an optional
237 <quote>detail
</quote> message; this is to be used when there is additional
238 information that seems inappropriate to put in the primary message.
239 The message string is processed in just the same way as for
240 <function>errmsg
</function>.
245 <function>errdetail_internal(const char *msg, ...)
</function> is the same
246 as
<function>errdetail
</function>, except that the message string will not be
247 translated nor included in the internationalization message dictionary.
248 This should be used for detail messages that are not worth expending
249 translation effort on, for instance because they are too technical to be
250 useful to most users.
255 <function>errdetail_plural(const char *fmt_singular, const char *fmt_plural,
256 unsigned long n, ...)
</function> is like
<function>errdetail
</function>, but with
257 support for various plural forms of the message.
258 For more information see
<xref linkend=
"nls-guidelines"/>.
263 <function>errdetail_log(const char *msg, ...)
</function> is the same as
264 <function>errdetail
</function> except that this string goes only to the server
265 log, never to the client. If both
<function>errdetail
</function> (or one of
266 its equivalents above) and
267 <function>errdetail_log
</function> are used then one string goes to the client
268 and the other to the log. This is useful for error details that are
269 too security-sensitive or too bulky to include in the report
275 <function>errdetail_log_plural(const char *fmt_singular, const char
276 *fmt_plural, unsigned long n, ...)
</function> is like
277 <function>errdetail_log
</function>, but with support for various plural forms of
279 For more information see
<xref linkend=
"nls-guidelines"/>.
284 <function>errhint(const char *msg, ...)
</function> supplies an optional
285 <quote>hint
</quote> message; this is to be used when offering suggestions
286 about how to fix the problem, as opposed to factual details about
288 The message string is processed in just the same way as for
289 <function>errmsg
</function>.
294 <function>errhint_plural(const char *fmt_singular, const char *fmt_plural,
295 unsigned long n, ...)
</function> is like
<function>errhint
</function>, but with
296 support for various plural forms of the message.
297 For more information see
<xref linkend=
"nls-guidelines"/>.
302 <function>errcontext(const char *msg, ...)
</function> is not normally called
303 directly from an
<function>ereport
</function> message site; rather it is used
304 in
<literal>error_context_stack
</literal> callback functions to provide
305 information about the context in which an error occurred, such as the
306 current location in a PL function.
307 The message string is processed in just the same way as for
308 <function>errmsg
</function>. Unlike the other auxiliary functions, this can
309 be called more than once per
<function>ereport
</function> call; the successive
310 strings thus supplied are concatenated with separating newlines.
315 <function>errposition(int cursorpos)
</function> specifies the textual location
316 of an error within a query string. Currently it is only useful for
317 errors detected in the lexical and syntactic analysis phases of
323 <function>errtable(Relation rel)
</function> specifies a relation whose
324 name and schema name should be included as auxiliary fields in the error
330 <function>errtablecol(Relation rel, int attnum)
</function> specifies
331 a column whose name, table name, and schema name should be included as
332 auxiliary fields in the error report.
337 <function>errtableconstraint(Relation rel, const char *conname)
</function>
338 specifies a table constraint whose name, table name, and schema name
339 should be included as auxiliary fields in the error report. Indexes
340 should be considered to be constraints for this purpose, whether or
341 not they have an associated
<structname>pg_constraint
</structname> entry. Be
342 careful to pass the underlying heap relation, not the index itself, as
343 <literal>rel
</literal>.
348 <function>errdatatype(Oid datatypeOid)
</function> specifies a data
349 type whose name and schema name should be included as auxiliary fields
355 <function>errdomainconstraint(Oid datatypeOid, const char *conname)
</function>
356 specifies a domain constraint whose name, domain name, and schema name
357 should be included as auxiliary fields in the error report.
362 <function>errcode_for_file_access()
</function> is a convenience function that
363 selects an appropriate SQLSTATE error identifier for a failure in a
364 file-access-related system call. It uses the saved
365 <literal>errno
</literal> to determine which error code to generate.
366 Usually this should be used in combination with
<literal>%m
</literal> in the
367 primary error message text.
372 <function>errcode_for_socket_access()
</function> is a convenience function that
373 selects an appropriate SQLSTATE error identifier for a failure in a
374 socket-related system call.
379 <function>errhidestmt(bool hide_stmt)
</function> can be called to specify
380 suppression of the
<literal>STATEMENT:
</literal> portion of a message in the
381 postmaster log. Generally this is appropriate if the message text
382 includes the current statement already.
387 <function>errhidecontext(bool hide_ctx)
</function> can be called to
388 specify suppression of the
<literal>CONTEXT:
</literal> portion of a message in
389 the postmaster log. This should only be used for verbose debugging
390 messages where the repeated inclusion of context would bloat the log
399 At most one of the functions
<function>errtable
</function>,
400 <function>errtablecol
</function>,
<function>errtableconstraint
</function>,
401 <function>errdatatype
</function>, or
<function>errdomainconstraint
</function> should
402 be used in an
<function>ereport
</function> call. These functions exist to
403 allow applications to extract the name of a database object associated
404 with the error condition without having to examine the
405 potentially-localized error message text.
406 These functions should be used in error reports for which it's likely
407 that applications would wish to have automatic error handling. As of
408 <productname>PostgreSQL
</productname> 9.3, complete coverage exists only for
409 errors in SQLSTATE class
23 (integrity constraint violation), but this
410 is likely to be expanded in future.
415 There is an older function
<function>elog
</function> that is still heavily used.
416 An
<function>elog
</function> call:
418 elog(level,
"format string", ...);
420 is exactly equivalent to:
422 ereport(level, errmsg_internal(
"format string", ...));
424 Notice that the SQLSTATE error code is always defaulted, and the message
425 string is not subject to translation.
426 Therefore,
<function>elog
</function> should be used only for internal errors and
427 low-level debug logging. Any message that is likely to be of interest to
428 ordinary users should go through
<function>ereport
</function>. Nonetheless,
429 there are enough internal
<quote>cannot happen
</quote> error checks in the
430 system that
<function>elog
</function> is still widely used; it is preferred for
431 those messages for its notational simplicity.
435 Advice about writing good error messages can be found in
436 <xref linkend=
"error-style-guide"/>.
440 <sect1 id=
"error-style-guide">
441 <title>Error Message Style Guide
</title>
444 This style guide is offered in the hope of maintaining a consistent,
445 user-friendly style throughout all the messages generated by
446 <productname>PostgreSQL
</productname>.
449 <simplesect id=
"error-style-guide-what-goes-where">
450 <title>What Goes Where
</title>
453 The primary message should be short, factual, and avoid reference to
454 implementation details such as specific function names.
455 <quote>Short
</quote> means
<quote>should fit on one line under normal
456 conditions
</quote>. Use a detail message if needed to keep the primary
457 message short, or if you feel a need to mention implementation details
458 such as the particular system call that failed. Both primary and detail
459 messages should be factual. Use a hint message for suggestions about what
460 to do to fix the problem, especially if the suggestion might not always be
465 For example, instead of:
467 IpcMemoryCreate: shmget(key=%d, size=%u,
0%o) failed: %m
468 (plus a long addendum that is basically a hint)
472 Primary: could not create shared memory segment: %m
473 Detail: Failed syscall was shmget(key=%d, size=%u,
0%o).
474 Hint: The addendum, written as a complete sentence.
479 Rationale: keeping the primary message short helps keep it to the point,
480 and lets clients lay out screen space on the assumption that one line is
481 enough for error messages. Detail and hint messages can be relegated to a
482 verbose mode, or perhaps a pop-up error-details window. Also, details and
483 hints would normally be suppressed from the server log to save
484 space. Reference to implementation details is best avoided since users
485 aren't expected to know the details.
490 <simplesect id=
"error-style-guide-formatting">
491 <title>Formatting
</title>
494 Don't put any specific assumptions about formatting into the message
495 texts. Expect clients and the server log to wrap lines to fit their own
496 needs. In long messages, newline characters (\n) can be used to indicate
497 suggested paragraph breaks. Don't end a message with a newline. Don't
498 use tabs or other formatting characters. (In error context displays,
499 newlines are automatically added to separate levels of context such as
504 Rationale: Messages are not necessarily displayed on terminal-type
505 displays. In GUI displays or browsers these formatting instructions are
511 <simplesect id=
"error-style-guide-quotation-marks">
512 <title>Quotation Marks
</title>
515 English text should use double quotes when quoting is appropriate.
516 Text in other languages should consistently use one kind of quotes that is
517 consistent with publishing customs and computer output of other programs.
521 Rationale: The choice of double quotes over single quotes is somewhat
522 arbitrary, but tends to be the preferred use. Some have suggested
523 choosing the kind of quotes depending on the type of object according to
524 SQL conventions (namely, strings single quoted, identifiers double
525 quoted). But this is a language-internal technical issue that many users
526 aren't even familiar with, it won't scale to other kinds of quoted terms,
527 it doesn't translate to other languages, and it's pretty pointless, too.
532 <simplesect id=
"error-style-guide-quotes">
533 <title>Use of Quotes
</title>
536 Always use quotes to delimit file names, user-supplied identifiers,
537 configuration variable names, and other variables that might contain
538 words. Do not use them to mark up variables that will not contain words
539 (for example, operator names).
543 There are functions in the backend that will double-quote their own output
544 as needed (for example,
<function>format_type_be()
</function>). Do not put
545 additional quotes around the output of such functions.
549 Rationale: Objects can have names that create ambiguity when embedded in a
550 message. Be consistent about denoting where a plugged-in name starts and
551 ends. But don't clutter messages with unnecessary or duplicate quote
557 <simplesect id=
"error-style-guide-grammar-punctuation">
558 <title>Grammar and Punctuation
</title>
561 The rules are different for primary error messages and for detail/hint
566 Primary error messages: Do not capitalize the first letter. Do not end a
567 message with a period. Do not even think about ending a message with an
572 Detail and hint messages: Use complete sentences, and end each with
573 a period. Capitalize the first word of sentences. Put two spaces after
574 the period if another sentence follows (for English text; might be
575 inappropriate in other languages).
579 Error context strings: Do not capitalize the first letter and do
580 not end the string with a period. Context strings should normally
581 not be complete sentences.
585 Rationale: Avoiding punctuation makes it easier for client applications to
586 embed the message into a variety of grammatical contexts. Often, primary
587 messages are not grammatically complete sentences anyway. (And if they're
588 long enough to be more than one sentence, they should be split into
589 primary and detail parts.) However, detail and hint messages are longer
590 and might need to include multiple sentences. For consistency, they should
591 follow complete-sentence style even when there's only one sentence.
596 <simplesect id=
"error-style-guide-case">
597 <title>Upper Case vs. Lower Case
</title>
600 Use lower case for message wording, including the first letter of a
601 primary error message. Use upper case for SQL commands and key words if
602 they appear in the message.
606 Rationale: It's easier to make everything look more consistent this
607 way, since some messages are complete sentences and some not.
612 <simplesect id=
"error-style-guide-passive-voice">
613 <title>Avoid Passive Voice
</title>
616 Use the active voice. Use complete sentences when there is an acting
617 subject (
<quote>A could not do B
</quote>). Use telegram style without
618 subject if the subject would be the program itself; do not use
619 <quote>I
</quote> for the program.
623 Rationale: The program is not human. Don't pretend otherwise.
628 <simplesect id=
"error-style-guide-tense">
629 <title>Present vs. Past Tense
</title>
632 Use past tense if an attempt to do something failed, but could perhaps
633 succeed next time (perhaps after fixing some problem). Use present tense
634 if the failure is certainly permanent.
638 There is a nontrivial semantic difference between sentences of the form:
640 could not open file
"%s": %m
644 cannot open file
"%s"
646 The first one means that the attempt to open the file failed. The
647 message should give a reason, such as
<quote>disk full
</quote> or
648 <quote>file doesn't exist
</quote>. The past tense is appropriate because
649 next time the disk might not be full anymore or the file in question might
654 The second form indicates that the functionality of opening the named file
655 does not exist at all in the program, or that it's conceptually
656 impossible. The present tense is appropriate because the condition will
657 persist indefinitely.
661 Rationale: Granted, the average user will not be able to draw great
662 conclusions merely from the tense of the message, but since the language
663 provides us with a grammar we should use it correctly.
668 <simplesect id=
"error-style-guide-object-type">
669 <title>Type of the Object
</title>
672 When citing the name of an object, state what kind of object it is.
676 Rationale: Otherwise no one will know what
<quote>foo.bar.baz
</quote>
682 <simplesect id=
"error-style-guide-brackets">
683 <title>Brackets
</title>
686 Square brackets are only to be used (
1) in command synopses to denote
687 optional arguments, or (
2) to denote an array subscript.
691 Rationale: Anything else does not correspond to widely-known customary
692 usage and will confuse people.
697 <simplesect id=
"error-style-guide-error-messages">
698 <title>Assembling Error Messages
</title>
701 When a message includes text that is generated elsewhere, embed it in
704 could not open file %s: %m
709 Rationale: It would be difficult to account for all possible error codes
710 to paste this into a single smooth sentence, so some sort of punctuation
711 is needed. Putting the embedded text in parentheses has also been
712 suggested, but it's unnatural if the embedded text is likely to be the
713 most important part of the message, as is often the case.
718 <simplesect id=
"error-style-guide-error-reasons">
719 <title>Reasons for Errors
</title>
722 Messages should always state the reason why an error occurred.
725 BAD: could not open file %s
726 BETTER: could not open file %s (I/O failure)
728 If no reason is known you better fix the code.
733 <simplesect id=
"error-style-guide-function-names">
734 <title>Function Names
</title>
737 Don't include the name of the reporting routine in the error text. We have
738 other mechanisms for finding that out when needed, and for most users it's
739 not helpful information. If the error text doesn't make as much sense
740 without the function name, reword it.
742 BAD: pg_strtoint32: error in
"z": cannot parse
"z"
743 BETTER: invalid input syntax for type integer:
"z"
748 Avoid mentioning called function names, either; instead say what the code
751 BAD: open() failed: %m
752 BETTER: could not open file %s: %m
754 If it really seems necessary, mention the system call in the detail
755 message. (In some cases, providing the actual values passed to the
756 system call might be appropriate information for the detail message.)
760 Rationale: Users don't know what all those functions do.
765 <simplesect id=
"error-style-guide-tricky-words">
766 <title>Tricky Words to Avoid
</title>
769 <title>Unable
</title>
771 <quote>Unable
</quote> is nearly the passive voice. Better use
772 <quote>cannot
</quote> or
<quote>could not
</quote>, as appropriate.
779 Error messages like
<quote>bad result
</quote> are really hard to interpret
780 intelligently. It's better to write why the result is
<quote>bad
</quote>,
781 e.g.,
<quote>invalid format
</quote>.
786 <title>Illegal
</title>
788 <quote>Illegal
</quote> stands for a violation of the law, the rest is
789 <quote>invalid
</quote>. Better yet, say why it's invalid.
794 <title>Unknown
</title>
796 Try to avoid
<quote>unknown
</quote>. Consider
<quote>error: unknown
797 response
</quote>. If you don't know what the response is, how do you know
798 it's erroneous?
<quote>Unrecognized
</quote> is often a better choice.
799 Also, be sure to include the value being complained of.
801 BAD: unknown node type
802 BETTER: unrecognized node type:
42
808 <title>Find vs. Exists
</title>
810 If the program uses a nontrivial algorithm to locate a resource (e.g., a
811 path search) and that algorithm fails, it is fair to say that the program
812 couldn't
<quote>find
</quote> the resource. If, on the other hand, the
813 expected location of the resource is known but the program cannot access
814 it there then say that the resource doesn't
<quote>exist
</quote>. Using
815 <quote>find
</quote> in this case sounds weak and confuses the issue.
820 <title>May vs. Can vs. Might
</title>
822 <quote>May
</quote> suggests permission (e.g.,
"You may borrow my rake."),
823 and has little use in documentation or error messages.
824 <quote>Can
</quote> suggests ability (e.g.,
"I can lift that log."),
825 and
<quote>might
</quote> suggests possibility (e.g.,
"It might rain
826 today."). Using the proper word clarifies meaning and assists
832 <title>Contractions
</title>
834 Avoid contractions, like
<quote>can't
</quote>; use
835 <quote>cannot
</quote> instead.
840 <title>Non-negative
</title>
842 Avoid
<quote>non-negative
</quote> as it is ambiguous
843 about whether it accepts zero. It's better to use
844 <quote>greater than zero
</quote> or
845 <quote>greater than or equal to zero
</quote>.
851 <simplesect id=
"error-style-guide-spelling">
852 <title>Proper Spelling
</title>
855 Spell out words in full. For instance, avoid:
886 Rationale: This will improve consistency.
891 <simplesect id=
"error-style-guide-localization">
892 <title>Localization
</title>
895 Keep in mind that error message texts need to be translated into other
896 languages. Follow the guidelines in
<xref linkend=
"nls-guidelines"/>
897 to avoid making life difficult for translators.
903 <sect1 id=
"source-conventions">
904 <title>Miscellaneous Coding Conventions
</title>
906 <simplesect id=
"source-conventions-c-standard">
907 <title>C Standard
</title>
909 Code in
<productname>PostgreSQL
</productname> should only rely on language
910 features available in the C99 standard. That means a conforming
911 C99 compiler has to be able to compile postgres, at least aside
912 from a few platform dependent pieces.
915 A few features included in the C99 standard are, at this time, not
916 permitted to be used in core
<productname>PostgreSQL
</productname>
917 code. This currently includes variable length arrays, intermingled
918 declarations and code,
<literal>//
</literal> comments, universal
919 character names. Reasons for that include portability and historical
923 Features from later revisions of the C standard or compiler specific
924 features can be used, if a fallback is provided.
927 For example
<literal>_Static_assert()
</literal> and
928 <literal>__builtin_constant_p
</literal> are currently used, even though
929 they are from newer revisions of the C standard and a
930 <productname>GCC
</productname> extension respectively. If not available
931 we respectively fall back to using a C99 compatible replacement that
932 performs the same checks, but emits rather cryptic messages and do not
933 use
<literal>__builtin_constant_p
</literal>.
937 <simplesect id=
"source-conventions-macros-inline">
938 <title>Function-Like Macros and Inline Functions
</title>
940 Both macros with arguments and
<literal>static inline
</literal>
941 functions may be used. The latter are preferable if there are
942 multiple-evaluation hazards when written as a macro, as e.g., the
945 #define Max(x, y) ((x)
> (y) ? (x) : (y))
947 or when the macro would be very long. In other cases it's only
948 possible to use macros, or at least easier. For example because
949 expressions of various types need to be passed to the macro.
952 When the definition of an inline function references symbols
953 (i.e., variables, functions) that are only available as part of the
954 backend, the function may not be visible when included from frontend
958 static inline MemoryContext
959 MemoryContextSwitchTo(MemoryContext context)
961 MemoryContext old = CurrentMemoryContext;
963 CurrentMemoryContext = context;
966 #endif /* FRONTEND */
968 In this example
<literal>CurrentMemoryContext
</literal>, which is only
969 available in the backend, is referenced and the function thus
970 hidden with a
<literal>#ifndef FRONTEND
</literal>. This rule
971 exists because some compilers emit references to symbols
972 contained in inline functions even if the function is not used.
976 <simplesect id=
"source-conventions-signal-handlers">
977 <title>Writing Signal Handlers
</title>
979 To be suitable to run inside a signal handler code has to be
980 written very carefully. The fundamental problem is that, unless
981 blocked, a signal handler can interrupt code at any time. If code
982 inside the signal handler uses the same state as code outside
983 chaos may ensue. As an example consider what happens if a signal
984 handler tries to acquire a lock that's already held in the
988 Barring special arrangements code in signal handlers may only
989 call async-signal safe functions (as defined in POSIX) and access
990 variables of type
<literal>volatile sig_atomic_t
</literal>. A few
991 functions in
<command>postgres
</command> are also deemed signal safe, importantly
992 <function>SetLatch()
</function>.
995 In most cases signal handlers should do nothing more than note
996 that a signal has arrived, and wake up code running outside of
997 the handler using a latch. An example of such a handler is the
1001 handle_sighup(SIGNAL_ARGS)
1010 <simplesect id=
"source-conventions-function-pointers">
1011 <title>Calling Function Pointers
</title>
1014 For clarity, it is preferred to explicitly dereference a function pointer
1015 when calling the pointed-to function if the pointer is a simple variable,
1018 (*emit_log_hook) (edata);
1020 (even though
<literal>emit_log_hook(edata)
</literal> would also work).
1021 When the function pointer is part of a structure, then the extra
1022 punctuation can and usually should be omitted, for example:
1024 paramInfo-
>paramFetch(paramInfo, paramId);