Types and encodings
types, encoding, decimal, datetime
Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.
A value in memory (types::Value) is 32 bytes on 64-bit targets — a
tag and up to 24: a string, a decimal (its 128-bit mantissa aligned to 8
bytes, repr(C, packed(8))), an address; an enum’s value behind an Arc —
checked when the crate compiles (§M14.20 W5: it was 64, which every row
and batch paid).
| Type | Names | Value |
|---|---|---|
| boolean | BOOLEAN, BOOL |
|
| smallint | SMALLINT, INT2 |
16-bit |
| integer | INTEGER, INT, INT4 |
32-bit |
| bigint | BIGINT, INT8 (and, with pg-compat, OID) |
64-bit |
| real | REAL, FLOAT4 |
32-bit IEEE 754 |
| double precision | DOUBLE PRECISION, FLOAT, FLOAT8 |
64-bit IEEE 754 |
| numeric | NUMERIC [(p, s)], DECIMAL, DEC |
exact: 128-bit mantissa and a scale, ≤ 38 digits |
| text | TEXT, VARCHAR(n) (and, with pg-compat, NAME) |
VARCHAR(n) length enforced |
| character | CHAR(n), CHARACTER(n) (CHAR is CHAR(1); with pg-compat, BPCHAR) |
blank-padded |
| bytea | BYTEA |
a binary string |
| date | DATE |
days since 2000-01-01, 4713 BC – 294276 AD |
| time | TIME [WITHOUT TIME ZONE] |
µs since midnight, 00:00 – 24:00 |
| timestamp | TIMESTAMP [WITHOUT TIME ZONE] |
µs since 2000-01-01 |
| timestamptz | TIMESTAMPTZ, TIMESTAMP WITH TIME ZONE |
µs since 2000-01-01 UTC |
| interval | INTERVAL |
months, days, µs (kept apart) |
| inet | INET |
an IPv4 or IPv6 address, optionally with a mask length |
| cidr | CIDR |
an IPv4 or IPv6 network (host bits zero) |
| arrays | type[] |
one dimension, elements of the type or NULL |
| uuid | UUID |
16 bytes, a registered type (§8.12) |
| vector | VECTOR, VECTOR(n) |
1–16000 float4 components, a registered type (§8.12) |
| sparsevec | SPARSEVEC, SPARSEVEC(n) |
up to 10⁹ dimensions, 16000 of them non-zero, a registered type (§8.12) |
| json | JSON, JSONB |
a JSON value in a binary form read in place, a registered type (§8.31) |
| enums | CREATE TYPE name AS ENUM (…) |
a label of the database’s enum |
| registered types | their name (geopoint) |
a module’s type: its canonical bytes (§8.12) |
uuid is the first type built as a registered one (uuid.rs):
input as 32 hex digits in either case, a hyphen allowed after any group of
four, optionally in braces; output lower case 8-4-4-4-12; equality,
hashing, ordering (byte order, as PostgreSQL’s) and a fixed 16-byte key
encoding, so it can be a primary key or indexed; casts to and from
text; min / max (from its ordering — PostgreSQL has none).
Functions: gen_random_uuid() / uuidv4() (version 4, from the
platform’s unpredictable randomness), uuidv7() (version 7: unix
milliseconds, 12 bits of the millisecond’s fraction, random bits;
increasing within a process — the recommended key, new rows land at the
end of the index), uuid_extract_version(u) (for RFC 9562 variants),
uuid_extract_timestamp(u) (versions 1 and 7). crates/testkit/slt/20_uuid.slt’s
expected results came from PostgreSQL 18.
vector (vectors.rs, §M14.12) is built the same way, on every
capability a type can have. Its canonical bytes are its components as
little-endian f32s (-0 stored as 0, so equal vectors are equal
bytes); text '[1,2.5,-3]', each component printed in the shorter of its
shortest decimal and exponent forms (1e-7); NaN, infinities, an empty
vector and more than 16000 components refused — a driver’s parameter or
loaded value checked from its bytes as the text is (Type::wire_input;
a sparsevec‘s too), not formatted and parsed again. vector(n) checks the
dimensions on every write and cast (22000, “expected 3 dimensions, not
2”; nc_catalog.columns shows vector(3)). Casts to and from real[]
(and from any numeric array; a NULL element is 23502) and text.
Equality and hashing on the bytes (DISTINCT, GROUP BY, UNIQUE,
hash joins); a total order — component by component, then the shorter
first — with an order-preserving key encoding (01, then per component
its sortable big-endian bits, 00 at the end), so a vector can be a
primary key, sorted and B-tree indexed. Distances: <-> Euclidean (the
type’s Distance), and as operators <=> cosine (NaN for a zero vector,
as pgvector), <#> the negated inner product, <+> taxicab; as functions
l2_distance, cosine_distance, negative_inner_product,
inner_product, l1_distance. Each is a nucleus-kernels kernel over
the stored bytes — sixteen running f32 sums added in a fixed order, so
the result is the same bits at every SIMD level (NEON, AVX2, AVX-512) —
and ORDER BY v <-> $1 LIMIT k is an exact nearest-neighbour search (a
top-k over the scan). Vectors of different dimensions are 22000.
Arithmetic component by component (+, -, *) and ||
(concatenation), the type’s Arithmetic; functions vector_dims /
dims, vector_norm / l2_norm / norm, l2_normalize / normalize
(a zero vector stays zero), subvector(v, from, count). Components by
position (the type’s Elements, the same mechanism as arrays’): v[i]
a real, 1-based, NULL out of range; v[lo:hi] a vector, bounds
clamped, an empty slice 22023; UPDATE … SET v[i] = x inside the
vector’s dimension (2202E outside it, 22000 for a NULL component).
Aggregates sum
and avg (centroids), each component summed exactly (fsum::ExactSum,
§M14.27) and rounded once. crates/testkit/slt/45_vector.slt follows
pgvector’s definitions.
sparsevec (sparse.rs, §M14.12 V6b): a vector of many dimensions
of which few are not zero — a learned sparse model’s term weights
(SPLADE), a bag of words — kept as its non-zero components. Its
canonical bytes are its dimensions and its non-zero count (little-endian
u32s), their positions (0-based, ascending, u32s) and their values
(f32s); text pgvector’s '{1:0.5,4:2}/10' (positions from 1, in any
order; zeros, -0 too, dropped). At most 1,000,000,000 dimensions and
16,000 non-zero components; a position outside the dimensions or twice,
NaN, infinities 22000 / 22003. sparsevec(n) checks the dimensions
on every write. Bytes from a driver (ncp tag 11, pgvector’s binary form
on pg-compat) are checked as text is and kept canonical (§10). Equality and hashing on the bytes (no order). Distances
over the positions merged, read in place from the stored bytes (View:
nothing allocated): <-> Euclidean (the type’s), <=> cosine (NaN for a
zero vector), <#> the negated inner product, <+> taxicab — the same
operators and functions as vector‘s (l2_distance, cosine_distance,
inner_product, negative_inner_product, l1_distance, l2_norm,
l2_normalize take either: vectors::VectorFn resolves by its
arguments’ type). Casts to and from vector. ORDER BY v <#> q LIMIT k is an exact search (a scan and a top-k per morsel on the workers,
merged — vector::sorted, as every ORDER BY … LIMIT over a scan:
100,000 SPLADE-like rows in docs/benchmarks.md); an HNSW index refuses the type (0A000) — sparse
vectors’ index is an inverted one, USING sparse (§8.21), which ranks
<#> exactly.
crates/testkit/slt/54_sparsevec.slt follows pgvector’s definitions; the
law kit generates them.
Integers by width. An integer literal is integer if it fits, else
bigint (PostgreSQL’s rule). Arithmetic on two integers has the wider
operand’s type (smallint + smallint is smallint, smallint + integer
integer) and overflows at that width (22003, integer out of range);
so does a function whose result is a narrow integer (abs(-32768::smallint)).
Casts between widths and from numeric (half away from zero) or double precision (half to even, as PostgreSQL’s rint) check the range; text
input takes an optional sign, decimal digits, or 0x / 0o / 0b ones,
_ between digits (PostgreSQL 16), and spaces around — out of range is
22003 (value "40000" is out of range for type smallint). sum of
smallint or integer is bigint, avg of any integer numeric;
count is bigint; length, strpos, array_length and date - date
are integer. Columns are range-checked on every write. Values are one
64-bit integer in memory; the row encoding stores each in the fewest of 2,
4 or 8 bytes that holds it, and keys hold every width in 8, so an index
serves a comparison across widths and widening a column keeps its keys.
crates/testkit/slt/23_integers.slt (and pg-compat’s 02_types.slt for
the types, through pg_typeof) came from PostgreSQL 18.
real and double precision. A float prints as PostgreSQL 12+
prints it: the shortest digits that read back to the same value, in fixed
notation when the leading digit’s power of ten is from −4 up to 14 (a
double) or 5 (a real), else as 1.2345679e+08; -0, NaN,
Infinity. Input out of range — beyond the largest, or nonzero digits
that round to zero — is 22003 ("1e40" is out of range for type real), as is an arithmetic result that overflows or underflows (value out of range: overflow). real with real is computed in 32 bits and
is real; real with any other number is double precision
(PostgreSQL has no mixed real operators), but CASE, UNION and
greatest unify real with integers and numeric as real. sum of
reals is real, avg a double; round, trunc, floor, ceil and
sign of a real are a double’s, and round of a float is half to even
(rint). A real becomes numeric through 6 significant digits, a double
through 15. A real is stored in 4 bytes (row tag 14); keys widen it to a
double’s encoding, so an index on a real serves double bounds.
crates/testkit/slt/24_real.slt came from PostgreSQL 18.
bytea (bytea.rs): input as \x and hex digit pairs (spaces
between pairs allowed) or the escape form (characters as their UTF-8
bytes, \\ a backslash, \ooo an octal byte); output the hex form
(\xdeadbeef); a text literal or text casts to it by its input form, and
it casts to text as its output. Byte-wise order (a shorter prefix
first), key tag 0C (its bytes escaped as text’s), row tag 15. ||,
length and octet_length (bytes), substring / substr (also
substring(x FROM a FOR b)), position(sub IN x), get_byte,
set_byte, encode(b, 'hex' | 'base64' | 'escape') (base64 lines of 76
characters, as PostgreSQL’s) and decode, sha256 (bytea) and md5
(text or bytea, a hex text) — the digests built in, without a
dependency. crates/testkit/slt/25_bytea.slt came from PostgreSQL 18.
char(n) follows the standard: a value is stored padded with blanks
to n; a longer one is 22001 unless the excess is blanks, and an
explicit cast truncates. Trailing blanks do not count: in comparisons
(with another char, or as text with text), keys (stored without them),
length, || and the cast to text (which drop them), and functions
taking text; octet_length and LIKE see the padded value, as
PostgreSQL’s. char with text unifies to text. Key tag 0E, row
tag 18. Columns declared char(n) before §M14.26 were text and open
as text. crates/testkit/slt/27_char.slt came from PostgreSQL 18.
inet and cidr (inet.rs): input as PostgreSQL’s — dotted IPv4,
IPv6 with :: and an embedded IPv4 tail, /bits; a cidr refuses host
bits set (22P02) and takes abbreviated IPv4 (10, 192.168/16, the
mask from the address class when omitted). Output: an inet without
/bits at a full mask, a cidr always with it, IPv6 lower case with the
longest run of zero groups as :: and ::ffff:a.b.c.d dotted. Order:
IPv4 first, then the address masked to its mask length, the mask length,
the whole address — PostgreSQL’s — in which a network’s addresses are one
contiguous range; keys follow it (tag 0F), and an inet equals a
cidr of the same value. Operators <<, <<=, >>, >>=, &&;
functions host, network, masklen, family, broadcast, netmask,
hostmask, abbrev, set_masklen, inet_same_family; casts between
them (to cidr clears the host bits) and from text. x <<= net and
x << net imply x lies between net and its broadcast address at a
full mask: the binder adds those bounds (the functions’
implied_range, §8.12), so an index on x serves containment as a
range scan. crates/testkit/slt/28_inet.slt came from PostgreSQL 18.
Enums (enums.rs): CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'), ordered by declaration; ALTER TYPE mood ADD VALUE [IF NOT EXISTS] 'meh' [BEFORE | AFTER 'ok'], ALTER TYPE mood RENAME VALUE 'sad' TO 'blue', DROP TYPE [IF EXISTS] mood (refused, 2BP01, while a column
has it). An enum is the database’s, in its catalog (00 09 <name>), and
transactional as the rest of it. Each label has a sort key, a base-256
fraction between 0 and 1 without trailing zero bytes (byte order is its
order); a value is stored as its key alone (key tag 10, row tag 21),
and there is always room between two keys, so a new label goes anywhere
and a renamed one keeps its key: neither rewrites a row (a test compares
the table’s bytes). Reading a row gives each value its label
(enums::Labels, one catalog read per enum and scan); text becomes an
enum where a transaction is at hand — binding, a cast as it runs,
assignment to a column — and a parameter for one arrives as its label.
Values of different enums do not compare (42883); an unknown label is
22P02. Arrays of enums: not yet. nc_catalog.enums lists the labels
with their keys. crates/testkit/slt/29_enum.slt came from PostgreSQL
18.
time: input as HH:MM[:SS[.f]], HHMM, HHMMSS, with AM /
PM, or allballs (a zone after it is ignored, as PostgreSQL’s time
does; 24:00:00 is the end of the day, a leap second rounds into it);
out of range is 22008, bad syntax 22007. time ± interval (the
interval’s time part, around the clock), time - time (an interval),
date + time (a timestamp); casts from timestamps and intervals (their
time of day) and to an interval; extract / date_part of hour,
minute, second, milliseconds, microseconds, epoch (others are
0A000, as PostgreSQL’s); make_time(h, m, s), localtime. Key tag
0D, row tag 17. time(p) is accepted and µs are kept (as for
timestamps); time with time zone is refused (0A000) — timestamptz
covers what it would. crates/testkit/slt/26_time.slt came from
PostgreSQL 18.
INSERT … VALUES binds each value against its target column, as
PostgreSQL does: an untyped literal takes the column’s type, and each row’s
value is converted as it is stored rather than unified with the other rows’
(VALUES ('-inf'), (1.5) into a real column).
Before widths (table record version 5 and older), INT, INTEGER and
SMALLINT columns were 64-bit with BIGINT’s column tag, so the catalog
cannot tell them apart: such a database opens with them as bigint, its
values intact; ALTER TABLE … ALTER c TYPE integer narrows one, checking
every value. Likewise REAL columns were double precision and open as
one.
Decimal literals (1.5, 1e3) are numeric, as in PostgreSQL; integers
too big for bigint too; only values beyond numeric’s 38 digits fall back to
double. Numeric arithmetic is exact and never rounds silently (overflow is
22003): +/- keep the larger scale, * adds them, / keeps at least
16 significant digits (PostgreSQL’s rule); rounding is half away from zero;
NUMERIC(p, s) rounds to s and checks p. Numbers compare across
types (numeric against double as doubles); dates and timestamps compare
across each other (a date as its midnight); intervals by their span (a
month as 30 days). avg of integers is numeric.
Date/time: sessions are in UTC. Input YYYY-MM-DD, YYYY-MM-DD[ T]HH:MM[:SS [.f]][zone] (Z, UTC, ±HH[:MM]; ignored for timestamp), epoch,
BC; intervals as N unit … (µs to millennia, fractions spill into
smaller units), [-]H:M[:S], @ … ago, ISO 8601 P…. Output is
PostgreSQL’s ISO style (2024-03-10 12:05:06+00, 1 year 2 mons 3 days 04:05:06). Arithmetic: date ± int, date - date, ± interval (months
by the calendar, the day clamped), timestamp - timestamp (days and
time), interval × / number. Typed literals: DATE '…', INTERVAL '…',
any type 'text'. Arrays: '{a,"b c",NULL}', ARRAY[…],
ARRAY(subquery), a[i] (1-based, NULL out of range), slices
a[lo:hi] / a[:hi] / a[lo:] (bounds clamped, PostgreSQL’s), UPDATE … SET a[i] = x (the array grown with NULLs, a NULL array taken as empty,
2202E below 1 or for a NULL position), ||.
Key encoding (order-preserving, self-delimiting): 00 NULL; 01 bool;
02 + i ^ i64::MIN big-endian; 03 + sign-flipped/inverted IEEE bits
(-0 = 0, one NaN above everything); 04 + text with 00 → 00 FF,
terminated 00 01; 05 numeric (sign class, decimal exponent, digits;
equal values of different scale share a key); 06 date; 07/08
timestamps; 09 interval (its span); 0A arrays (each element after
01, a NULL element as 02 — after the others, as comparisons have
it — then 00); 0B a registered type (its stable id, then its own key
encoding). Key encoding version 2 (the format record, §8.2): version 1
wrote a NULL array element as 01 00, before the others — the law kit
caught the disagreement — and the first write to a version-1 database
rewrites the keys of every table with an array in a key
(dml::rewrite_keys; the decoder reads both). Row encoding: version 04, column count, the
offsets of columns 16, 32, … (u16 from the row’s start; FFFF for one
past 64 KiB, reached by reading on from the mark before it), tagged values
(missing trailing columns read as NULL — or as a column’s value kept
for the rows stored before it was added, Table::missing — so ADD COLUMN needs no rewrite unless its default differs from row to row); an integer is tag 12 (2 bytes), 13 (4) or
2 (8), the fewest that hold it (version 01, still read, had only 2);
a real is tag 14, a bytea 15; a registered type’s value is tag 11,
its id, its encoding version and its canonical bytes; tag 16 (a
u32 length) is a value stored out of line; text, char(n), bytea and
an enum shorter than 256 bytes are tags 22–25 with a u8 length
rather than a u32; a decimal is tag 26 (its scale, then its mantissa
in 4 bytes) or 27 (in 8) where the mantissa fits, else 05 (16 bytes
and the scale) — 6 or 10 bytes for most where 05 took 18 (issue #2:
TPC-H lineitem’s four decimals 72 → 24 bytes a row) (encoding::RowWriter,
encode_row_value; the wire keeps encode_value’s). A scan reading a few of a row’s columns jumps
to the mark before each and skips the values between (RowHeader::seek,
for the row-at-a-time and the batch decoders alike: a value of a tag of
one length, or a short text, passed over by the length its tag gives —
a table, encoding::FIXED — the row’s end checked once; issue #2: TPC-H
Q6, seven values passed over a row, −8 %). Versions 02 (no
offsets, no tags 22–25) and 03 (no tags 26, 27) still read; a
row is written in 04 when next written (§M14.20 W7, D18).
Large values out of line (large). A value whose encoding is longer
than 2 000 bytes (large::THRESHOLD) — a file in a bytea, a document
in a text, any type but one whose values are read with their row
(Type::stored_with_row: vector, sparsevec — kept in the row, on
the KV’s overflow pages past 2,048 bytes, one read with its key;
large::out_of_line_value, §M14.12 V7.2) — is stored in chunks of up to 32 KiB under the
table’s reserved index id FFFFFFFF, keyed by the row’s primary key, the
column and the chunk number; the row keeps tag 16 and the length, and
reads (large::read_row) put the value back. The chunks are written and
removed with their row, in its transaction: a snapshot sees the chunks of
the row version it sees, a rollback or a crash leaves none behind (the
crash test writes large values), a changed primary key moves them, and
dropping the table removes them. An update that leaves a large value as
it was writes none of its chunks. A batch scan of the rows
(RowBatches) reads the values it needs through large::Chunks: one
scan of the chunks from the first row holding one to the scan’s end,
walked beside the rows’ (the chunks’ keys follow the rows’), each
value’s chunks read until they hold its length and a one-chunk value
decoded from the chunk as read — a step a value where a seek was
(§M14.12 V2: a scan of 768-float vectors 2.3× faster on its own); the
row-at-a-time executor looks each value up (large::fetch). The
consistency check finds a value missing chunks and chunks without their
value. A registered type’s id is
the FNV-1a hash of its name, the same in every process (two names with
one id are refused when registered).
Every type is a Type (§8.12), the built-in ones included: the
binder, DDL and aggregates ask a type’s abilities before relying on them,
and refuse what it lacks at bind or DDL time, naming the ability — type geopoint has no ordering, which ORDER BY needs; it has a distance: ORDER BY x <-> value (42883), … no key encoding, which a primary key needs
(42704). Equality: =, <>, IN, simple CASE, JOIN USING;
equality and hashing: DISTINCT (also in aggregates), GROUP BY, UNION
(not ALL), INTERSECT, EXCEPT; ordering: < …, ORDER BY (also in
aggregates), min, max; key encoding (and equality for a primary key
or UNIQUE): keys and indexes. The built-in types have every ability
(their values are native, and the hot paths run native code).