API reference
PostgreSQL wire protocol in Zig: frontend and backend message codecs, with no IO and no allocator.
Callers provide every buffer. frame.Decoder finds message boundaries and
hands out headers and body runs; the codecs that read a body into a message
sit above it.
const pg = @import("pg");
var decoder: pg.frame.Decoder = .init();
var rest = chunk_from_the_socket;
while (rest.len != 0 or decoder.inMessage()) {
const step = try decoder.next(rest);
rest = rest[step.consumed..];
switch (step.event) {
.header => |header| {
const tag = try pg.messages.Backend.fromByte(header.tag);
// ... decode header.bodyLength() bytes from the body runs
},
.body => |complete| if (complete) { ... },
.more => break,
}
}
module
backend
src
Backend messages: the ones a server sends.
more
Decoding borrows the body. A message with a list in it, which is DataRow,
RowDescription, and the copy responses among others, keeps the body and
hands out an iterator, because a client cannot know how many columns fit a
fixed buffer and this layer does not allocate.
Encoding reads the same union backwards. A message decoded here keeps the
body it came from, so write re-emits it and a proxy can forward a message
it never interpreted. The field-wise writers cover the messages whose shape
is values rather than bytes: CommandComplete, ParameterStatus,
NotificationResponse, BackendKeyData, ReadyForQuery,
FunctionCallResponse, and Authentication.
What is missing is constructing a backend message from values, which is a
server's shape: a DataRow built from columns rather than re-emitted from a
body. That arrives with a caller.
Constants
G. The server wants copy-in data.
H. The server is about to send copy-out data.
W. Streaming replication only: both directions at once.
Types
union
Message
src
pub const Message = union(messages.Backend)
One decoded backend message.
Fields
authentication: Authentication
backend_key_data: BackendKeyData
bind_complete: BindComplete
close_complete: CloseComplete
command_complete: CommandComplete
copy_both_response: CopyBoth
copy_data: CopyData
copy_done: CopyDone
copy_in_response: CopyIn
copy_out_response: CopyOut
data_row: DataRow
empty_query_response: EmptyQueryResponse
error_response: ErrorResponse
function_call_response: FunctionCallResponse
negotiate_protocol_version: NegotiateProtocolVersion
no_data: NoData
notice_response: NoticeResponse
notification_response: NotificationResponse
parameter_description: ParameterDescription
parameter_status: ParameterStatus
parse_complete: ParseComplete
portal_suspended: PortalSuspended
ready_for_query: ReadyForQuery
row_description: RowDescription
Functions
Decode one body, given the tag byte from its frame.
more
Derived from the union: an arm's name is a field of
messages.Backend, so the mapping from tag to decoder is the union
itself and adding an arm adds its decoder.
A tag this library does not name is error.UnknownTag rather than a
panic, so a caller can forward it or fail on its own terms.
union
Authentication
src
pub const Authentication = union(enum)
R. Which login method the server wants next.
Fields
ok ok
kerberos_v5 kerberos_v5
cleartext_password cleartext_password
md5_password: [4]u8
The four bytes to salt the MD5 digest.
gss gss
gss_continue: []const u8
sspi sspi
sasl: Sasl
sasl_continue: []const u8
sasl_final: []const u8
unknown: u32
A code this library does not name. The server will not continue a login the client cannot answer.
Functions
struct
Sasl
src
The mechanism names an AuthenticationSASL offers, in the server's order of
preference, each null-terminated with a final null.
Fields
mechanisms: []const u8
Functions
struct
BackendKeyData
src
K. The cancel key, to send in CancelRequest on another connection.
Fields
Functions
struct
CommandComplete
src
C. The command tag, such as INSERT 0 3 or SELECT 2.
Fields
tag: []const u8
Functions
struct
ReadyForQuery
src
Z. The server is ready for another cycle, and the transaction state.
Fields
status: messages.Transaction
Functions
struct
ParameterStatus
src
S. A run-time parameter, sent at connect and again whenever it changes.
Fields
Functions
struct
NotificationResponse
src
A. A LISTEN/NOTIFY delivery, arriving between messages.
Fields
Functions
struct
DataRow
src
D. One row.
Two sources, told apart by body: a row that arrived borrows the frame and
its values come from values, and a row built by a server or a proxy
writes built. columns is the count of a decoded row; a built one counts
built.
Fields
body: []const u8 = ""
columns: u16 = 0
built: []const ?[]const u8 = &.{}
The values to send, where a null is a SQL NULL.
Functions
The number of columns, either way.
The values, in column order. A null is a SQL NULL.
Types
struct
RowDescription
src
T. The columns a result will return, before the rows.
Two sources, told apart by body: a description that arrived borrows the
frame and its columns come from columns, and one built by a server or a
proxy writes built.
Fields
Functions
Types
struct
ParameterDescription
src
t. The parameter types a prepared statement resolved to.
Fields
Functions
Types
struct
NegotiateProtocolVersion
src
v. The server speaks an older minor version than the client asked for, or
it ignored some startup options.
Fields
Functions
pub fn unrecognized(self: *const NegotiateProtocolVersion) Options
src
Types
struct
ErrorResponse
src
E. A failed statement. The connection stays up unless the severity says
otherwise.
Two sources, told apart by body: a message that arrived keeps its bytes
and re-emits them, and a message a server or a proxy makes up writes the
fields below. fields iterates the wire form, so it is empty on a message
that was built rather than read.
Fields
body: []const u8 = ""
severity: ?Severity = null
S, the severity, localized by the server that sent it.
severity_unlocalized: ?Severity = null
V, the same severity in English. PostgreSQL sends both; a message
built here sends whichever are set.
code: ?sqlstate.SqlState = null
C.
message: ?[]const u8 = null
M.
Functions
struct
NoticeResponse
src
N. A warning, a notice, or a server-side log line, carrying the same
fields an error does.
Fields
body: []const u8
Functions
struct
FunctionCallResponse
src
V. The result of the obsolete fast-path function call.
Fields
value: ?[]const u8
Null when the function returned NULL.
Functions
module
error_response
src
ErrorResponse and NoticeResponse bodies.
more
E and N carry the same body: a sequence of a field code byte and a
null-terminated value, ended by a zero byte. Fields can arrive in any order,
each at most once, and the protocol says a frontend ignores a code it does
not know — so this yields the raw code and leaves the meaning to the caller.
What arrives is not necessarily one kind of failure: NoticeResponse is the
same format for a notice, a warning, or a server-side log line, and a
decision about which of those is fatal belongs above this layer.
Functions
An ErrorResponse or NoticeResponse body.
Types
struct
Field
src
Fields
code: u8
The code byte, exactly as sent. kind names it when this library knows
it, which is not a condition for keeping it.
value: []const u8
The value bytes, borrowed from the message body.
Functions
The code, when this field carries one.
A field of the right kind with the wrong length is a malformed message, so this says null rather than inventing a code.
The value as an integer, for the P and L fields.
more
Those fields are plain decimal ASCII, so no sign and no base prefix: a
+, a -, or a space is error.InvalidCharacter, and a value too
large for u32 is error.Overflow. std.fmt.parseInt takes all of
those, which would turn a server bug into a position.
module
frame
src
PostgreSQL message framing: a tag byte, a big-endian int32 length, and a body.
more
The length counts itself and the body but not the tag, so a message with an empty body declares 4 and occupies 5 bytes. It must be at least 4, and the server refuses anything of 1 GiB or more.
The decoder never holds a body. It reports a header, then hands back body
bytes in the runs the caller feeds it, so a DataRow larger than the read
buffer costs nothing. A message with an empty body reports its header and
then one .body with complete, which consumes nothing: drive the loop on
in_message as well as on unread bytes.
Constants
pub const max_length: u32 = 1 << 30
src
The largest message the protocol allows. The server's cap is below 2^30 bytes, and a length near 2^31 would overflow the arithmetic that windows a body.
value
error{
/// A length below 4 counts less than the field that holds it.
InvalidLength,
/// A length of 1 GiB or more.
MessageTooLong,
}Types
struct
Header
src
A parsed header.
Fields
tag: u8
The tag byte. Which enum it belongs to depends on who sent the message,
so the decoder leaves it raw: messages.Backend.fromByte.
length: u32
The whole message after the tag, including these four bytes.
Functions
pub fn bodyLength(self: Header) u32
src
The bytes between the length and the next tag.
struct
Decoder
src
Finds message boundaries in a stream, in place.
Fields
bytes: [5]u8
The tag, then the four length bytes, collected across however many reads it takes.
filled: u3
remaining: u32
Body bytes still owed to the current message.
in_message: bool
Constants
value
.{
.bytes = undefined,
.filled = 0,
.remaining = 0,
.in_message = false,
}Functions
Drop a partial message, for a connection that is being torn down.
An error from next means the bytes stopped lining up with a message
boundary. The decoder is left clean rather than stuck, so a caller that
ignored the error would read the middle of a message as a header and
get plausible nonsense back. Drop the connection instead of calling
this.
Take as much of data as the current message needs.
At most one event per call. Every event but .more consumes at least
one byte, so .more is the only time a caller loops without progress.
Types
module
frontend
src
Frontend messages: the ones a client sends.
more
Message is a union tagged by messages.Frontend, so the arm name and the
tag byte are the same fact. Each arm holds a value whose write emits the
fields in the order the docs list them; the union writes the tag and the
length. That is what makes it impossible for a Query to carry a parse
tag.
The bytes of a message that never varies are built at comptime in fixed,
from these same writers.
Types
struct
Bind
src
B. Bind a prepared statement to a portal, with the values.
Fields
portal: []const u8 = ""
statement: []const u8 = ""
formats: []const Format = &.{}
No format codes means text for every parameter, one applies to all, and otherwise there is one per parameter.
parameters: []const ?[]const u8 = &.{}
result_formats: []const Format = &.{}
The same three shapes as formats, for the result columns.
Functions
struct
FunctionCall
src
F. Call a function directly, one round trip and no SQL. Obsolete: the
extended protocol replaced it, and the server still accepts it.
Fields
function: u32
formats: []const Format = &.{}
arguments: []const ?[]const u8 = &.{}
result_format: Format = .text
Functions
struct
SaslInitial
src
A SASLInitialResponse: the mechanism the client chose and its first
message.
Fields
mechanism: []const u8
response: ?[]const u8
Null when the client sent no initial response, which the wire marks with a length of -1 rather than a zero length.
Functions
union
Password
src
pub const Password = union(enum)
p. The one tag four messages share. Which one this is comes from the
authentication conversation, not from the byte, so a writer names it.
Fields
cleartext: []const u8
PasswordMessage: the password, null-terminated.
sasl_initial: SaslInitial
SASLInitialResponse.
sasl_response: []const u8
SASLResponse: mechanism data, with no length and no terminator.
gss: []const u8
GSSResponse: the same shape as a SASL response.
Functions
struct
PasswordBody
src
A decoded p body, for the server side.
The body is kept as it arrived, because the four messages it could be are told apart by the conversation rather than by the tag. The accessors are how a caller who knows asks.
Fields
body: []const u8
Functions
PasswordMessage: a null-terminated password.
pub fn saslInitial(self: *const PasswordBody) DecodeError!SaslInitial
src
A SASLResponse or a GSSResponse, which are the bytes as sent.
union
Message
src
pub const Message = union(messages.Frontend)
A frontend message, one arm per tag a client can send.
The tag is messages.Frontend, so an arm's name is its wire byte and the
union cannot be a version of the protocol behind the enum it is tagged by.
Fields
bind: Bind
close: Close
describe: Describe
execute: Execute
function_call: FunctionCall
flush: Flush
parse: Parse
query: Query
sync: Sync
terminate: Terminate
copy_data: CopyData
copy_done: CopyDone
copy_fail: CopyFail
password: Password
Functions
struct
BindView
src
A decoded Bind. Formats come in the same three shapes the encoder takes,
so a caller reads the count and then decides.
Fields
body: []const u8
portal: []const u8
statement: []const u8
formats_at: wire.Reader
Positioned at the first parameter format code.
format_count: u16
values_at: wire.Reader
Positioned at the first parameter value.
value_count: u16
results_at: wire.Reader
Positioned at the first result format code.
result_count: u16
Functions
pub fn resultFormats(self: *const BindView) wire.U16s
src
struct
FunctionCallView
src
A decoded FunctionCall, the same shape as a decoded Bind.
Fields
body: []const u8
function: u32
formats_at: wire.Reader
Positioned at the first argument format code.
format_count: u16
values_at: wire.Reader
Positioned at the first argument value.
value_count: u16
result_format: u16
Functions
union
Decoded
src
pub const Decoded = union(messages.Frontend)
A decoded frontend message: the shape a server or a proxy reads.
Three of these are views, because their lists have no fixed size. The rest are the same values a client writes, since every field they carry is a borrowed slice or a number.
Fields
bind: BindView
close: Close
describe: Describe
execute: Execute
function_call: FunctionCallView
flush: Flush
parse: ParseView
query: Query
sync: Sync
terminate: Terminate
copy_data: CopyData
copy_done: CopyDone
copy_fail: CopyFail
password: PasswordBody
Functions
struct
fixed
src
Messages whose bytes never vary, built by running their encoder at comptime.
Constants
pub const bind_empty = write.build(.{ .bind = .{} })
src
Bind the unnamed portal to the unnamed statement, with no parameters and no format codes.
pub const describe_portal = write.build(.{ .describe = .{ .target = .portal } })
src
Describe the unnamed portal.
pub const execute_portal = write.build(.{ .execute = .{} })
src
Execute the unnamed portal with no row limit.
module
messages
src
PostgreSQL wire protocol message tags, and the messages whose bytes are constant.
more
Every message outside the startup phase starts with a tag byte. The length
and the body are frame.zig's business. The startup messages carry no tag
and are not here.
Tags are not unique across directions. d and c are copy data and copy
done both ways, p is a password or a SASL or GSS response depending on
when it is sent, and R covers a dozen authentication variants. The enums
below are per direction; whatever resolves the rest is the connection
state machine, not this file.
https://www.postgresql.org/docs/current/protocol-message-formats.html
Types
enum
Frontend
src
pub const Frontend = enum(u8)
Frontend to backend messages. A client encodes these; only a server or a proxy decodes them.
Fields
bind bind = 'B'
close close = 'C'
describe describe = 'D'
execute execute = 'E'
function_call function_call = 'F'
flush flush = 'H'
parse parse = 'P'
query query = 'Q'
sync sync = 'S'
terminate terminate = 'X'
copy_data copy_data = 'd'
copy_done copy_done = 'c'
copy_fail copy_fail = 'f'
password password = 'p'
Password, SASL initial response, SASL response, or GSS response. The tag alone does not say which; the authentication conversation does.
_ _
A tag this library does not name. The wire can carry one: a newer
server, a proxy, or a byte that is not a tag at all. A switch over the
enum reaches its else arm, and the caller decides what to do.
Functions
enum
Backend
src
pub const Backend = enum(u8)
Backend to frontend messages. A client decodes these; only a server or a proxy encodes them.
Fields
authentication authentication = 'R'
Every authentication variant shares this tag. The first int32 of the
body selects one through Auth.
backend_key_data backend_key_data = 'K'
bind_complete bind_complete = '2'
close_complete close_complete = '3'
command_complete command_complete = 'C'
copy_both_response copy_both_response = 'W'
copy_data copy_data = 'd'
copy_done copy_done = 'c'
copy_in_response copy_in_response = 'G'
copy_out_response copy_out_response = 'H'
data_row data_row = 'D'
empty_query_response empty_query_response = 'I'
error_response error_response = 'E'
function_call_response function_call_response = 'V'
negotiate_protocol_version negotiate_protocol_version = 'v'
no_data no_data = 'n'
notice_response notice_response = 'N'
notification_response notification_response = 'A'
parameter_description parameter_description = 't'
parameter_status parameter_status = 'S'
parse_complete parse_complete = '1'
portal_suspended portal_suspended = 's'
ready_for_query ready_for_query = 'Z'
row_description row_description = 'T'
_ _
A tag this library does not name. The wire can carry one: a newer
server, a proxy, or a byte that is not a tag at all. A switch over the
enum reaches its else arm, and the caller decides what to do.
Functions
enum
Transaction
src
pub const Transaction = enum(u8)
The transaction status that a ReadyForQuery carries.
Fields
idle idle = 'I'
Not in a transaction block.
in_block in_block = 'T'
In a transaction block.
failed failed = 'E'
In a failed transaction block; queries are rejected until it ends.
_ _
A status byte this library does not name.
Functions
enum
Auth
src
pub const Auth = enum(u32)
The first int32 of an authentication message.
Fields
ok ok = 0
kerberos_v5 kerberos_v5 = 2
cleartext_password cleartext_password = 3
md5_password md5_password = 5
The body carries four bytes of salt after this word.
gss gss = 7
gss_continue gss_continue = 8
sspi sspi = 9
sasl sasl = 10
The body carries the mechanism names, each null-terminated, then a final null.
sasl_continue sasl_continue = 11
sasl_final sasl_final = 12
_ _
An authentication code this library does not name.
Functions
enum
ErrorField
src
pub const ErrorField = enum(u8)
ErrorResponse and NoticeResponse field codes.
more
The registry is open. The protocol says a frontend silently ignores a field
code it does not know, so an unknown code stays an unknown value: it
compares equal to none of the fields below and falls into the else arm.
A field appears at most once in a message, in any order, and the body ends with a zero byte.
Fields
severity severity = 'S'
S. Localized.
severity_unlocalized severity_unlocalized = 'V'
V. Never localized; present from PostgreSQL 9.6.
code code = 'C'
C. The SQLSTATE code.
message message = 'M'
detail detail = 'D'
hint hint = 'H'
position position = 'P'
P. A one-based character index into the submitted query, not bytes.
internal_position internal_position = 'p'
p. The same, for a command the server generated itself.
internal_query internal_query = 'q'
q. The text of that generated command.
where where = 'W'
W. A call stack of procedures and generated queries, most recent
first.
schema schema = 's'
table table = 't'
column column = 'c'
data_type data_type = 'd'
constraint constraint = 'n'
file file = 'F'
line line = 'L'
routine routine = 'R'
_ _
A field code this library does not name. The protocol says to ignore it, and an unknown code compares equal to none of the fields above.
Functions
module
print
src
Printing a value for a log line or a test failure.
A message has one useful rendering for a human, and it is not its bytes. Two rules keep a debug print safe: a string is quoted and escaped so a newline in a query cannot split a log line, and a value that can be huge or secret prints as a size instead of its contents.
Functions
Bytes as a quoted string, with the escapes std.zig.stringEscape makes.
The name of a tag, or null when this library does not declare it.
For a caller that formats its own way, such as JSON, which wants the name without punctuation.
An enum from the wire: its tag name when this library declares that tag, and the number when it does not.
{t} on an unknown value of a non-exhaustive enum panics, and a decoder
can produce one from any byte, so a log line cannot use it. This is the
fuzzer's first find.
A value whose contents stay out of the line: a password, or a copy stream.
Types
module
replication
src
The messages that ride inside a copy-both stream.
more
A client asks for replication with the replication startup parameter. The
server answers CopyBothResponse and from then on both directions carry
CopyData, whose payload starts with one of these tags instead of a message
tag. There is no length field of their own: the CopyData length is the
only boundary, so a message here runs to the end of the payload it was
handed.
The WAL inside XLogData has its own format, negotiated by
proto_version. Logical decoding output (the pgoutput stream) is a
decoder above this one, not another arm here.
https://www.postgresql.org/docs/current/protocol-replication.html
Types
enum
Kind
src
pub const Kind = enum(u8)
The first byte of a copy-both payload.
Fields
xlog_data xlog_data = 'w'
WAL from the server.
keepalive keepalive = 'k'
The server asking whether the standby is alive.
standby_status standby_status = 'r'
The standby saying how far it has got.
hot_standby_feedback hot_standby_feedback = 'h'
The standby holding back the server's vacuum.
_ _
Functions
struct
XLogData
src
w. A section of the WAL stream.
Fields
start: i64
Where this section starts in the WAL.
end: i64
The end of the WAL on the server when this was sent.
clock: i64
The server's clock, in microseconds since 2000-01-01.
data: []const u8
The WAL itself, borrowed from the copy payload.
Functions
struct
StandbyStatus
src
r. How far the standby has written, flushed, and applied.
Fields
written: i64
The last WAL byte received, plus one.
flushed: i64
The last WAL byte flushed to disk, plus one.
applied: i64
The last WAL byte applied, plus one.
clock: i64
The standby's clock, in microseconds since 2000-01-01.
reply: bool
Ask the server to answer at once, which is how a standby pings.
Functions
struct
HotStandbyFeedback
src
h. The standby's oldest transaction, so the server does not vacuum what a
running query still needs.
Fields
clock: i64
The standby's clock, in microseconds since 2000-01-01.
xmin: u32
The standby's oldest transaction.
xmin_epoch: u32
catalog_xmin: u32
The oldest of any replication slot on the standby, or zero.
catalog_xmin_epoch: u32
Functions
union
Message
src
pub const Message = union(Kind)
One message of the copy-both stream.
Fields
xlog_data: XLogData
keepalive: Keepalive
standby_status: StandbyStatus
hot_standby_feedback: HotStandbyFeedback
Functions
Decode one CopyData payload.
A tag this library does not name is error.UnknownTag, so a caller can
skip a message from a newer server instead of failing the stream.
Write one payload, without a CopyData around it.
module
sqlstate
src
SQLSTATE codes: the five-byte code a PostgreSQL error carries.
more
The code is the enum tag. Five ASCII bytes pack into a u40 big-endian, so
a named code and a code this table does not name are the same kind of value
and cost the same to compare, switch on, or print. format rebuilds the
five bytes from the tag, so an unknown code logs as itself rather than as a
number.
The variants are the condition names the standard gives, in the order
Appendix A lists them, with a comment per class. The set is open: the enum
is non-exhaustive because any five ASCII bytes are a legal code, an
extension can define more, and a client must not panic on one it has not
heard of. Five condition names are used by more than one class; the later
one carries its class as a suffix, as in null_value_not_allowed_39.
Generated from https://www.postgresql.org/docs/current/errcodes-appendix.html
if (field.state()) |state| switch (state) {
.unique_violation => ...,
else => ...,
};Constants
A code as a value: the five ASCII bytes packed big-endian into forty bits.
The number is the code, so a packed code compares, switches, and tags the
enum without a table. The bytes are how it travels, and that belongs to the
reader and the writer: stdx.wire.Reader reads a SqlState straight off
five bytes because the tag type is an integer.
The bytes a code occupies on the wire.
The length of a SQLSTATE code, in bytes.
Functions
Pack a code's bytes into its value. The first byte is the high byte, which is also the order the reader hands them over in. ziglint-ignore: Z012
Types
enum
SqlState
src
pub const SqlState = enum(Code)
Fields
successful_completion successful_completion = pack("00000")
A code as it appears on the wire, which is also its position in this list.
warning warning = pack("01000")
dynamic_result_sets_returned dynamic_result_sets_returned = pack("0100C")
implicit_zero_bit_padding implicit_zero_bit_padding = pack("01008")
null_value_eliminated_in_set_function null_value_eliminated_in_set_function = pack("01003")
privilege_not_granted privilege_not_granted = pack("01007")
privilege_not_revoked privilege_not_revoked = pack("01006")
string_data_right_truncation string_data_right_truncation = pack("01004")
deprecated_feature deprecated_feature = pack("01P01")
no_data no_data = pack("02000")
no_additional_dynamic_result_sets_returned no_additional_dynamic_result_sets_returned = pack("02001")
sql_statement_not_yet_complete sql_statement_not_yet_complete = pack("03000")
connection_exception connection_exception = pack("08000")
connection_does_not_exist connection_does_not_exist = pack("08003")
connection_failure connection_failure = pack("08006")
sqlclient_unable_to_establish_sqlconnection sqlclient_unable_to_establish_sqlconnection = pack("08001")
sqlserver_rejected_establishment_of_sqlconnection sqlserver_rejected_establishment_of_sqlconnection = pack("08004")
transaction_resolution_unknown transaction_resolution_unknown = pack("08007")
protocol_violation protocol_violation = pack("08P01")
triggered_action_exception triggered_action_exception = pack("09000")
feature_not_supported feature_not_supported = pack("0A000")
invalid_transaction_initiation invalid_transaction_initiation = pack("0B000")
locator_exception locator_exception = pack("0F000")
invalid_locator_specification invalid_locator_specification = pack("0F001")
invalid_grantor invalid_grantor = pack("0L000")
invalid_grant_operation invalid_grant_operation = pack("0LP01")
invalid_role_specification invalid_role_specification = pack("0P000")
diagnostics_exception diagnostics_exception = pack("0Z000")
stacked_diagnostics_accessed_without_active_handler stacked_diagnostics_accessed_without_active_handler = pack("0Z002")
invalid_argument_for_xquery invalid_argument_for_xquery = pack("10608")
case_not_found case_not_found = pack("20000")
cardinality_violation cardinality_violation = pack("21000")
data_exception data_exception = pack("22000")
array_subscript_error array_subscript_error = pack("2202E")
character_not_in_repertoire character_not_in_repertoire = pack("22021")
datetime_field_overflow datetime_field_overflow = pack("22008")
division_by_zero division_by_zero = pack("22012")
error_in_assignment error_in_assignment = pack("22005")
escape_character_conflict escape_character_conflict = pack("2200B")
indicator_overflow indicator_overflow = pack("22022")
interval_field_overflow interval_field_overflow = pack("22015")
invalid_argument_for_logarithm invalid_argument_for_logarithm = pack("2201E")
invalid_argument_for_ntile_function invalid_argument_for_ntile_function = pack("22014")
invalid_argument_for_nth_value_function invalid_argument_for_nth_value_function = pack("22016")
invalid_argument_for_power_function invalid_argument_for_power_function = pack("2201F")
invalid_argument_for_width_bucket_function invalid_argument_for_width_bucket_function = pack("2201G")
invalid_character_value_for_cast invalid_character_value_for_cast = pack("22018")
invalid_datetime_format invalid_datetime_format = pack("22007")
invalid_escape_character invalid_escape_character = pack("22019")
invalid_escape_octet invalid_escape_octet = pack("2200D")
invalid_escape_sequence invalid_escape_sequence = pack("22025")
nonstandard_use_of_escape_character nonstandard_use_of_escape_character = pack("22P06")
invalid_indicator_parameter_value invalid_indicator_parameter_value = pack("22010")
invalid_parameter_value invalid_parameter_value = pack("22023")
invalid_preceding_or_following_size invalid_preceding_or_following_size = pack("22013")
invalid_regular_expression invalid_regular_expression = pack("2201B")
invalid_row_count_in_limit_clause invalid_row_count_in_limit_clause = pack("2201W")
invalid_row_count_in_result_offset_clause invalid_row_count_in_result_offset_clause = pack("2201X")
invalid_tablesample_argument invalid_tablesample_argument = pack("2202H")
invalid_tablesample_repeat invalid_tablesample_repeat = pack("2202G")
invalid_time_zone_displacement_value invalid_time_zone_displacement_value = pack("22009")
invalid_use_of_escape_character invalid_use_of_escape_character = pack("2200C")
most_specific_type_mismatch most_specific_type_mismatch = pack("2200G")
null_value_not_allowed null_value_not_allowed = pack("22004")
null_value_no_indicator_parameter null_value_no_indicator_parameter = pack("22002")
numeric_value_out_of_range numeric_value_out_of_range = pack("22003")
sequence_generator_limit_exceeded sequence_generator_limit_exceeded = pack("2200H")
string_data_length_mismatch string_data_length_mismatch = pack("22026")
string_data_right_truncation_22 string_data_right_truncation_22 = pack("22001")
substring_error substring_error = pack("22011")
trim_error trim_error = pack("22027")
unterminated_c_string unterminated_c_string = pack("22024")
zero_length_character_string zero_length_character_string = pack("2200F")
floating_point_exception floating_point_exception = pack("22P01")
invalid_text_representation invalid_text_representation = pack("22P02")
invalid_binary_representation invalid_binary_representation = pack("22P03")
bad_copy_file_format bad_copy_file_format = pack("22P04")
untranslatable_character untranslatable_character = pack("22P05")
datum_version_mismatch datum_version_mismatch = pack("22P07")
not_an_xml_document not_an_xml_document = pack("2200L")
invalid_xml_document invalid_xml_document = pack("2200M")
invalid_xml_content invalid_xml_content = pack("2200N")
invalid_xml_comment invalid_xml_comment = pack("2200S")
invalid_xml_processing_instruction invalid_xml_processing_instruction = pack("2200T")
duplicate_json_object_key_value duplicate_json_object_key_value = pack("22030")
invalid_argument_for_sql_json_datetime_function invalid_argument_for_sql_json_datetime_function = pack("22031")
invalid_json_text invalid_json_text = pack("22032")
invalid_sql_json_subscript invalid_sql_json_subscript = pack("22033")
more_than_one_sql_json_item more_than_one_sql_json_item = pack("22034")
no_sql_json_item no_sql_json_item = pack("22035")
non_numeric_sql_json_item non_numeric_sql_json_item = pack("22036")
non_unique_keys_in_a_json_object non_unique_keys_in_a_json_object = pack("22037")
singleton_sql_json_item_required singleton_sql_json_item_required = pack("22038")
sql_json_array_not_found sql_json_array_not_found = pack("22039")
sql_json_member_not_found sql_json_member_not_found = pack("2203A")
sql_json_number_not_found sql_json_number_not_found = pack("2203B")
sql_json_object_not_found sql_json_object_not_found = pack("2203C")
too_many_json_array_elements too_many_json_array_elements = pack("2203D")
too_many_json_object_members too_many_json_object_members = pack("2203E")
sql_json_scalar_required sql_json_scalar_required = pack("2203F")
sql_json_item_cannot_be_cast_to_target_type sql_json_item_cannot_be_cast_to_target_type = pack("2203G")
integrity_constraint_violation integrity_constraint_violation = pack("23000")
restrict_violation restrict_violation = pack("23001")
not_null_violation not_null_violation = pack("23502")
foreign_key_violation foreign_key_violation = pack("23503")
unique_violation unique_violation = pack("23505")
check_violation check_violation = pack("23514")
exclusion_violation exclusion_violation = pack("23P01")
invalid_cursor_state invalid_cursor_state = pack("24000")
invalid_transaction_state invalid_transaction_state = pack("25000")
active_sql_transaction active_sql_transaction = pack("25001")
branch_transaction_already_active branch_transaction_already_active = pack("25002")
held_cursor_requires_same_isolation_level held_cursor_requires_same_isolation_level = pack("25008")
inappropriate_access_mode_for_branch_transaction inappropriate_access_mode_for_branch_transaction = pack("25003")
inappropriate_isolation_level_for_branch_transaction inappropriate_isolation_level_for_branch_transaction = pack("25004")
no_active_sql_transaction_for_branch_transaction no_active_sql_transaction_for_branch_transaction = pack("25005")
read_only_sql_transaction read_only_sql_transaction = pack("25006")
schema_and_data_statement_mixing_not_supported schema_and_data_statement_mixing_not_supported = pack("25007")
no_active_sql_transaction no_active_sql_transaction = pack("25P01")
in_failed_sql_transaction in_failed_sql_transaction = pack("25P02")
idle_in_transaction_session_timeout idle_in_transaction_session_timeout = pack("25P03")
transaction_timeout transaction_timeout = pack("25P04")
invalid_sql_statement_name invalid_sql_statement_name = pack("26000")
triggered_data_change_violation triggered_data_change_violation = pack("27000")
invalid_authorization_specification invalid_authorization_specification = pack("28000")
invalid_password invalid_password = pack("28P01")
dependent_privilege_descriptors_still_exist dependent_privilege_descriptors_still_exist = pack("2B000")
dependent_objects_still_exist dependent_objects_still_exist = pack("2BP01")
invalid_transaction_termination invalid_transaction_termination = pack("2D000")
sql_routine_exception sql_routine_exception = pack("2F000")
function_executed_no_return_statement function_executed_no_return_statement = pack("2F005")
modifying_sql_data_not_permitted modifying_sql_data_not_permitted = pack("2F002")
prohibited_sql_statement_attempted prohibited_sql_statement_attempted = pack("2F003")
reading_sql_data_not_permitted reading_sql_data_not_permitted = pack("2F004")
invalid_cursor_name invalid_cursor_name = pack("34000")
external_routine_exception external_routine_exception = pack("38000")
containing_sql_not_permitted containing_sql_not_permitted = pack("38001")
modifying_sql_data_not_permitted_38 modifying_sql_data_not_permitted_38 = pack("38002")
prohibited_sql_statement_attempted_38 prohibited_sql_statement_attempted_38 = pack("38003")
reading_sql_data_not_permitted_38 reading_sql_data_not_permitted_38 = pack("38004")
external_routine_invocation_exception external_routine_invocation_exception = pack("39000")
invalid_sqlstate_returned invalid_sqlstate_returned = pack("39001")
null_value_not_allowed_39 null_value_not_allowed_39 = pack("39004")
trigger_protocol_violated trigger_protocol_violated = pack("39P01")
srf_protocol_violated srf_protocol_violated = pack("39P02")
event_trigger_protocol_violated event_trigger_protocol_violated = pack("39P03")
savepoint_exception savepoint_exception = pack("3B000")
invalid_savepoint_specification invalid_savepoint_specification = pack("3B001")
invalid_catalog_name invalid_catalog_name = pack("3D000")
invalid_schema_name invalid_schema_name = pack("3F000")
transaction_rollback transaction_rollback = pack("40000")
transaction_integrity_constraint_violation transaction_integrity_constraint_violation = pack("40002")
serialization_failure serialization_failure = pack("40001")
statement_completion_unknown statement_completion_unknown = pack("40003")
deadlock_detected deadlock_detected = pack("40P01")
syntax_error_or_access_rule_violation syntax_error_or_access_rule_violation = pack("42000")
syntax_error syntax_error = pack("42601")
insufficient_privilege insufficient_privilege = pack("42501")
cannot_coerce cannot_coerce = pack("42846")
grouping_error grouping_error = pack("42803")
windowing_error windowing_error = pack("42P20")
invalid_recursion invalid_recursion = pack("42P19")
invalid_foreign_key invalid_foreign_key = pack("42830")
invalid_name invalid_name = pack("42602")
name_too_long name_too_long = pack("42622")
reserved_name reserved_name = pack("42939")
datatype_mismatch datatype_mismatch = pack("42804")
indeterminate_datatype indeterminate_datatype = pack("42P18")
collation_mismatch collation_mismatch = pack("42P21")
indeterminate_collation indeterminate_collation = pack("42P22")
wrong_object_type wrong_object_type = pack("42809")
generated_always generated_always = pack("428C9")
undefined_column undefined_column = pack("42703")
undefined_function undefined_function = pack("42883")
undefined_table undefined_table = pack("42P01")
undefined_parameter undefined_parameter = pack("42P02")
undefined_object undefined_object = pack("42704")
duplicate_column duplicate_column = pack("42701")
duplicate_cursor duplicate_cursor = pack("42P03")
duplicate_database duplicate_database = pack("42P04")
duplicate_function duplicate_function = pack("42723")
duplicate_prepared_statement duplicate_prepared_statement = pack("42P05")
duplicate_schema duplicate_schema = pack("42P06")
duplicate_table duplicate_table = pack("42P07")
duplicate_alias duplicate_alias = pack("42712")
duplicate_object duplicate_object = pack("42710")
ambiguous_column ambiguous_column = pack("42702")
ambiguous_function ambiguous_function = pack("42725")
ambiguous_parameter ambiguous_parameter = pack("42P08")
ambiguous_alias ambiguous_alias = pack("42P09")
invalid_column_reference invalid_column_reference = pack("42P10")
invalid_column_definition invalid_column_definition = pack("42611")
invalid_cursor_definition invalid_cursor_definition = pack("42P11")
invalid_database_definition invalid_database_definition = pack("42P12")
invalid_function_definition invalid_function_definition = pack("42P13")
invalid_prepared_statement_definition invalid_prepared_statement_definition = pack("42P14")
invalid_schema_definition invalid_schema_definition = pack("42P15")
invalid_table_definition invalid_table_definition = pack("42P16")
invalid_object_definition invalid_object_definition = pack("42P17")
with_check_option_violation with_check_option_violation = pack("44000")
insufficient_resources insufficient_resources = pack("53000")
disk_full disk_full = pack("53100")
out_of_memory out_of_memory = pack("53200")
too_many_connections too_many_connections = pack("53300")
configuration_limit_exceeded configuration_limit_exceeded = pack("53400")
program_limit_exceeded program_limit_exceeded = pack("54000")
statement_too_complex statement_too_complex = pack("54001")
too_many_columns too_many_columns = pack("54011")
too_many_arguments too_many_arguments = pack("54023")
object_not_in_prerequisite_state object_not_in_prerequisite_state = pack("55000")
object_in_use object_in_use = pack("55006")
cant_change_runtime_param cant_change_runtime_param = pack("55P02")
lock_not_available lock_not_available = pack("55P03")
unsafe_new_enum_value_usage unsafe_new_enum_value_usage = pack("55P04")
operator_intervention operator_intervention = pack("57000")
query_canceled query_canceled = pack("57014")
admin_shutdown admin_shutdown = pack("57P01")
crash_shutdown crash_shutdown = pack("57P02")
cannot_connect_now cannot_connect_now = pack("57P03")
database_dropped database_dropped = pack("57P04")
idle_session_timeout idle_session_timeout = pack("57P05")
system_error system_error = pack("58000")
io_error io_error = pack("58030")
undefined_file undefined_file = pack("58P01")
duplicate_file duplicate_file = pack("58P02")
file_name_too_long file_name_too_long = pack("58P03")
config_file_error config_file_error = pack("F0000")
lock_file_exists lock_file_exists = pack("F0001")
fdw_error fdw_error = pack("HV000")
fdw_column_name_not_found fdw_column_name_not_found = pack("HV005")
fdw_dynamic_parameter_value_needed fdw_dynamic_parameter_value_needed = pack("HV002")
fdw_function_sequence_error fdw_function_sequence_error = pack("HV010")
fdw_inconsistent_descriptor_information fdw_inconsistent_descriptor_information = pack("HV021")
fdw_invalid_attribute_value fdw_invalid_attribute_value = pack("HV024")
fdw_invalid_column_name fdw_invalid_column_name = pack("HV007")
fdw_invalid_column_number fdw_invalid_column_number = pack("HV008")
fdw_invalid_data_type fdw_invalid_data_type = pack("HV004")
fdw_invalid_data_type_descriptors fdw_invalid_data_type_descriptors = pack("HV006")
fdw_invalid_descriptor_field_identifier fdw_invalid_descriptor_field_identifier = pack("HV091")
fdw_invalid_handle fdw_invalid_handle = pack("HV00B")
fdw_invalid_option_index fdw_invalid_option_index = pack("HV00C")
fdw_invalid_option_name fdw_invalid_option_name = pack("HV00D")
fdw_invalid_string_length_or_buffer_length fdw_invalid_string_length_or_buffer_length = pack("HV090")
fdw_invalid_string_format fdw_invalid_string_format = pack("HV00A")
fdw_invalid_use_of_null_pointer fdw_invalid_use_of_null_pointer = pack("HV009")
fdw_too_many_handles fdw_too_many_handles = pack("HV014")
fdw_out_of_memory fdw_out_of_memory = pack("HV001")
fdw_no_schemas fdw_no_schemas = pack("HV00P")
fdw_option_name_not_found fdw_option_name_not_found = pack("HV00J")
fdw_reply_handle fdw_reply_handle = pack("HV00K")
fdw_schema_not_found fdw_schema_not_found = pack("HV00Q")
fdw_table_not_found fdw_table_not_found = pack("HV00R")
fdw_unable_to_create_execution fdw_unable_to_create_execution = pack("HV00L")
fdw_unable_to_create_reply fdw_unable_to_create_reply = pack("HV00M")
fdw_unable_to_establish_connection fdw_unable_to_establish_connection = pack("HV00N")
plpgsql_error plpgsql_error = pack("P0000")
raise_exception raise_exception = pack("P0001")
no_data_found no_data_found = pack("P0002")
too_many_rows too_many_rows = pack("P0003")
assert_failure assert_failure = pack("P0004")
internal_error internal_error = pack("XX000")
data_corrupted data_corrupted = pack("XX001")
index_corrupted index_corrupted = pack("XX002")
_ _
A code this table does not name. The set is open and any five ASCII bytes are legal, so this is reachable in normal operation rather than a broken invariant.
Functions
The bytes this code occupies on the wire.
A code from the bytes a message carried, named or not.
A code from a slice, or null when the length is wrong.
module
startup
src
The four messages that come before the protocol has tags.
more
Each is an int32 length that counts itself, then a body whose first four
bytes say which message this is: a protocol version for StartupMessage, or
one of three request codes. There is no tag byte and the length comes first,
which is why these cannot go through frame.Decoder.
https://www.postgresql.org/docs/current/protocol-message-formats.html
Constants
The version whose number doubles as the SSL request code: 1234 in the high
16 bits, 5679 in the low.
pub const cancel_code: u32 = 80877102
src
1234 and 5678.
pub const gssenc_code: u32 = 80877104
src
1234 and 5680.
The longest startup packet PostgreSQL accepts. Its backend refuses one
longer (MAX_STARTUP_PACKET_LENGTH), which is also what makes a peek at the
first bytes possible: a tagged message's tag in that position reads as a
length far past this.
Functions
The kind of message a connection is opening with, from at least eight bytes of it.
The length of a startup-phase message, from its first four bytes.
The whole message on the wire is exactly this many bytes, from the length field onward.
Types
enum
Kind
src
What the first bytes of a connection say it is.
A client's first message has no tag: four bytes of length, then a version or
a request code. A tagged message has its tag where the length would be, and
those four bytes read as a length past max_len, so an unrecognized prefix
is null rather than a guess.
Fields
struct
Startup
src
A StartupMessage: a version, then the parameters.
A message built by a client writes parameters. A message read off the
wire keeps the bytes it read in body and re-emits them, because a decoder
cannot build the slice without allocating and the bytes are already the
correct encoding.
Fields
version: Version = .v3_0
parameters: []const Parameter = &.{}
In any order. user is required by the server; everything else is a
run-time parameter, and names starting with _pq_. are reserved for
protocol extensions.
body: []const u8 = ""
The parameter bytes as they arrived, when this came from decode.
Functions
The parameters, in the order the client sent them.
Types
struct
Parameters
src
The parameters of a startup message, in the order sent.
Fields
reader: wire.Reader
Functions
struct
CancelRequest
src
A CancelRequest: the key a BackendKeyData handed out earlier.
Fields
Functions
union
Message
src
pub const Message = union(enum)
A message from before the tagged phase, or a request that ends the connection.
Fields
startup: Startup
ssl_request ssl_request
gssenc_request gssenc_request
cancel_request: CancelRequest
Functions
Decode one body: everything after the four-byte length.
module
Version
src
Protocol version numbers.
more
A version is four bytes on the wire: the major number, then the minor, each
big-endian. Protocol 3.0 is 00 03 00 00. The decimal in the documentation
(196608) is those same four bytes read as one big-endian word, and it is the
only place that word exists — toU32 and fromU32 are for logging and for
code that already has an integer, not for the wire.
The startup message sends this; the server answers with
NegotiateProtocolVersion when the client asks for a minor version it does
not support.
Constants
Protocol 3.0. What a client sends when it wants the 3.0 semantics,
including a four-byte BackendKeyData key.
Protocol 3.2, which PostgreSQL 18 describes. BackendKeyData and
CancelRequest keys became 4 to 256 bytes here.
Functions
The wire form, for a reader that already has four bytes in hand.
3.0, for a log line.
module
wire
src
The wire's cursor, and the one field shape stdx.wire does not cover.
more
stdx.wire.Reader(.big) and Writer(.big) do the work: fixed-width
integers and enums at comptime byte order, zero-copy slices, bounds checked
or asserted, and a reserved slot for the length a message only knows after
its body is written. This file names the big-endian pair and adds the
null-terminated string, which is the protocol's own field type.
Error is the reader's, so a parser's error set is the same whether it ran
out of bytes inside a take or inside a string.
Constants
Functions
pub fn takeString(r: *Reader) Error![]const u8
src
A null-terminated string, without the terminator.
The protocol calls this a String, and it appears in ErrorResponse,
RowDescription, ParameterStatus, StartupMessage, and the command
paths. The bytes are not UTF-8 validated: they are what the peer sent.
The next byte, without taking it.
Types
module
write
src
Writing a message: a tag, a length that counts itself, and a body.
more
stdx.wire.Writer(.big) does the fields. This adds the two things a
protocol message needs on top: the length is known only after the body, and
the body is written field by field in the order the docs give, with no
arithmetic at the call site.
A message that never varies is built at comptime by running its encoder and measuring the result, so the constant and the encoder cannot disagree.
Constants
Functions
A frontend message's bytes, built at comptime.
The parameter is the union rather than anytype so a call site can name
the arm: build(.{ .query = .{ .sql = "select 1" } }).
Types
struct
Encoder
src
A buffer, the message being written into it, and where that message began.
One encoder writes as many messages as fit, one after another. The buffer
belongs to the caller and never moves, which is what makes the length
backfill in finish safe.
Fields
writer: wire.Writer
at: u32
Where the current message began.
header: u1
How many bytes sit before the length field: one for a tag, none in the startup phase.
Constants
Functions
Start a frontend message: the tag, then four bytes of length to fill later.
pub fn startBackend(self: *Encoder, tag: messages.Backend) Error!void
src
Start a backend message. The same layout, on the other side of the connection.
pub fn startUntagged(self: *Encoder) Error!void
src
Start a message from before the tagged phase, where a length comes first and there is no tag byte.
Fill in the length and hand back the bytes of this message only.
The length counts itself and the body but not the tag, so a message with an empty body declares 4.
Where the buffer ends now, for a payload that has no length field of its own and is written whole by its caller.
The bytes written since mark.
Raw bytes, for a body field that is already in wire form.
A String: the bytes, then a zero. The protocol has no length field
for it, so a zero inside the value is not representable.