Documentation
¶
Overview ¶
Package id defines the canonical identifier used at repository interface boundaries, so a repository's callers never have to know whether a record lives in MongoDB (a 24-character hex ObjectID) or PostgreSQL (a UUID).
Resolving an old Mongo identifier ¶
An ObjectID-kind id is resolved against PostgreSQL by DERIVING the row's uuid, not by looking up a legacy_mongo_id column. shared/pgid reproduces mongo2pg's formula byte-for-byte and is pinned against vectors generated from mongo2pg itself; see its package doc for the contract.
Deriving is what lets legacy_mongo_id be dropped once the last pre-cutover credential has expired, costs no database round trip, and lets one service name a row in another service's database — a cross-service reference reached over gRPC — without a join.
The precondition, which is NOT enforced here ¶
The namespace is uuidv5(RootNS, serviceName + "/" + collection), so the SERVICE NAME the rows were migrated under decides every derived uuid. A self-hosted single-database deployment and a per-service production deployment can migrate the same collection under different service names, and then derive a different uuid from the same _id.
Nothing in this package can detect that. A service whose configured name does not match the mapping its rows were minted under derives well-formed uuids that name no row: reads come back empty and writes land unreferenced, with nothing logged. An earlier version of this doc cited exactly that risk as the reason not to derive at all; the decision went the other way, so the risk is now a deployment precondition rather than an avoided one. Whatever resolves the service name must agree with the mapping the data was replicated with.
Index ¶
- Variables
- func Compare(a, b ID) int
- func RegisterValidator(v *validator.Validate)
- func SetUUIDAccepted(accepted bool)
- func UUIDAccepted() bool
- type ID
- func (i ID) Equal(other ID) bool
- func (i ID) IsZero() bool
- func (i ID) Kind() Kind
- func (i ID) MarshalBSONValue() (bsontype.Type, []byte, error)
- func (i ID) MarshalText() ([]byte, error)
- func (i ID) ObjectID() (primitive.ObjectID, bool)
- func (i *ID) Scan(src any) error
- func (i ID) String() string
- func (i ID) UUID() (uuid.UUID, bool)
- func (i *ID) UnmarshalBSONValue(t bsontype.Type, data []byte) error
- func (i *ID) UnmarshalText(text []byte) error
- func (i ID) Value() (driver.Value, error)
- type Kind
Constants ¶
This section is empty.
Variables ¶
var ErrInvalid = errors.New("id: not a valid identifier")
ErrInvalid is the sentinel wrapped by every error Parse (and the other constructors in this package) return for input that is neither a 24-character hex Mongo ObjectID nor a UUID. Callers should use errors.Is against it rather than matching on Parse's error text, and — like syncquery.ErrInvalidCursor — must treat it as a hard failure (HTTP 400 at the API boundary) rather than silently ignoring the identifier.
Functions ¶
func Compare ¶
Compare orders two IDs without formatting either to a string: it returns a negative number, zero or a positive number as a sorts before, equal to or after b.
For two IDs of the SAME kind the order is the order of their canonical strings (lowercase hex ObjectIDs and hyphenated uuids are fixed-width and position-aligned, so byte order agrees with text order) — the order PostgreSQL and MongoDB give the same values. IDs of different kinds are ordered by kind, which carries no meaning: callers must not rely on it (see syncquery.Cursor.After, which drops the tie-break across kinds).
func RegisterValidator ¶
RegisterValidator teaches a validator to look through an ID. gin's binding validator is registered from init; a standalone validator.New() that validates structs carrying an ID must be passed here once.
func SetUUIDAccepted ¶
func SetUUIDAccepted(accepted bool)
SetUUIDAccepted configures whether Parse (and so every request-body, path-parameter and cursor id) accepts uuid text. db.Open calls it once at boot from the datasource: true on PostgreSQL, false on MongoDB.
The default is false, the MongoDB-safe setting. A service still on MongoDB stores ids as BSON ObjectIDs, and accepting a uuid-shaped string there would persist it as a BSON STRING, a dangling reference nothing could resolve. As on origin/dev, where ids were primitive.ObjectID, anything that is not 24 hex characters must be a 400 at bind time.
func UUIDAccepted ¶
func UUIDAccepted() bool
UUIDAccepted reports the setting SetUUIDAccepted configures.
Types ¶
type ID ¶
type ID struct {
// contains filtered or unexported fields
}
ID is the canonical neutral identifier. Its zero value (Kind == KindUnknown) is the id that names no record, the equivalent of primitive.NilObjectID: it is what Parse returns for the all-zero id and what FromObjectID / FromUUID return for the nil ObjectID / nil uuid. Always construct one through Parse or one of the other constructors below, never with a struct literal.
The parsed bytes are stored, not the text: a uuid occupies all 16 bytes of raw and an ObjectID the first 12 (the rest stay zero), so the canonical string is rendered on demand and nothing downstream (pgid, Value, the BSON codec) has to re-parse a value the constructors already validated. ID stays comparable: == agrees with Equal.
func FromObjectID ¶
FromObjectID builds an ID from an already-parsed Mongo ObjectID. The nil ObjectID returns the zero ID (IsZero true), so a caller holding an unset primitive.ObjectID cannot smuggle it past a zero-id guard.
func FromObjectIDHex ¶
FromObjectIDHex builds an ID from a Mongo ObjectID's hex string. It is equivalent to Parse but rejects a UUID, for call sites (Mongo repository implementations) that know their id must be an ObjectID and want that mismatch caught rather than silently accepted.
func FromUUID ¶
FromUUID builds an ID from an already-parsed uuid.UUID (e.g. one a PostgreSQL repository just generated for a new row). uuid.Nil returns the zero ID (IsZero true), for the same reason as FromObjectID.
func MustParse ¶
MustParse is Parse for call sites that already know raw is valid (tests, constants derived from literals). It panics on error — never use it on client-supplied input.
func Parse ¶
Parse normalises raw into the canonical ID form.
It accepts a 24-character hex Mongo ObjectID (either case) always, and a canonical 36-character hyphenated uuid only while the process runs on PostgreSQL (see SetUUIDAccepted). Nothing is trimmed: like primitive.ObjectIDFromHex before it, surrounding whitespace is a malformed id. Anything else — including an empty string, a malformed hex string, a mistyped uuid, or (on MongoDB) any uuid at all — is rejected with an error wrapping ErrInvalid. Parse never panics: bad client-supplied input (e.g. a corrupt cursor or path parameter) is exactly the case it exists to handle safely.
The all-zero id ("000000000000000000000000", or the nil uuid) parses to the ZERO ID, exactly as primitive.NilObjectID converts through FromObjectID. It is the id that names no record, so a lookup by it must answer not-found, as it did when ids were primitive.ObjectID. A caller that must refuse it (an authenticated identity) checks IsZero after parsing.
func (ID) IsZero ¶
IsZero reports whether i is the zero value: unset, or one of the nil ids (see Parse). Like primitive.ObjectID.IsZero it is what `bson:",omitempty"` consults, so an unset id is omitted from a document as it always was.
func (ID) MarshalBSONValue ¶
MarshalBSONValue writes an ObjectID-kind ID as a native BSON ObjectID, so the stored representation is byte-identical to what the same document held before this type existed. A UUID-kind ID is written as a string: Mongo has no uuid type, and a string keeps it greppable and comparable rather than hiding it in a binary subtype whose byte order is driver-dependent.
The zero ID marshals to the NIL ObjectID (000000000000000000000000), exactly what the primitive.ObjectID field it replaced wrote, rather than to BSON null or an error. It matters for queries: a filter such as bson.M{"user_id": zeroID} must match NOTHING, as it always did. Encoded as null it would match every document whose field is null or missing, which turns "no user resolved" into "every unowned row". A field tagged `omitempty` still omits a zero ID (the codec asks IsZero first), and decoding the nil ObjectID or null yields the zero ID again.
func (ID) MarshalText ¶
MarshalText implements encoding.TextMarshaler so an ID can be embedded directly in JSON API responses as a plain string. The zero ID renders as the nil ObjectID's text, the wire format an unset primitive.ObjectID had, on every datasource: it parses back to the zero ID in either mode.
func (ID) ObjectID ¶
ObjectID returns the ObjectID of an ObjectID-kind ID; ok is false for a uuid-kind ID.
The zero ID IS the nil ObjectID (FromObjectID(primitive.NilObjectID) is the zero ID), so it returns (primitive.NilObjectID, true): the inverse of FromObjectID for every ObjectID, the nil one included. A MongoDB lookup keyed by the result then matches nothing, as it did before ids were wrapped, instead of the caller mistaking an unknown id for a foreign-kind one and answering with an error. Callers that must refuse an unset id test IsZero.
func (ID) String ¶
String renders the canonical form: a lowercase 24-character hex string for an ObjectID-kind ID, or a lowercase hyphenated UUID string otherwise. The zero value renders as "".
func (*ID) UnmarshalBSONValue ¶
UnmarshalBSONValue accepts every shape an id can arrive in: a native ObjectID (what every existing document holds), a string (either form), a binary UUID, or null.
It accepts a string containing a UUID as well as one containing hex, because a document written by a service already migrated to PostgreSQL and then replicated back would carry exactly that.
func (*ID) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler using Parse, so a malformed identifier in a request body is rejected the same way a malformed path or query parameter is.
The empty string decodes to the zero ID, as it did for primitive.ObjectID (whose UnmarshalJSON turned "" into the nil ObjectID): a request body that carries `"id":""` for a not-yet-created record must bind. JSON null leaves the destination untouched (encoding/json never calls UnmarshalText for it), again as before. Whitespace is not trimmed: " " is malformed.
func (ID) Value ¶
Value implements driver.Valuer so an ID can be passed straight as a query argument. A UUID-kind ID is handed over as its canonical string, the one form every database/sql driver accepts as a driver.Value; PostgreSQL infers the parameter type from the `uuid` column it is compared with or inserted into, so it still binds natively and keeps using the index. An ObjectID-kind ID is an error (see below); the zero ID binds as NULL.
type Kind ¶
type Kind uint8
Kind reports which native form an ID was parsed from.
const ( // KindUnknown is the zero value: the ID was never successfully parsed. KindUnknown Kind = iota // KindObjectID means the ID's canonical form is a 24-character lowercase // hex Mongo ObjectID. KindObjectID // KindUUID means the ID's canonical form is a canonical (lowercase, // hyphenated) UUID string. KindUUID )