Skip to content

Latest commit

 

History

History
60 lines (37 loc) · 2.77 KB

README.md

File metadata and controls

60 lines (37 loc) · 2.77 KB

TypeID

TypeIDs are a draft standard for type-safe, globally unique identifiers based on the UUIDv7 standard. Their properties, particularly k-sortability, make them suitable primary identifiers for classic database systems like PostgreSQL. However, k-sortability may not always be desirable. For instance, you might require an identifier with high randomness entropy for security reasons. Additionally, in distributed database systems like CockroachDB, having a k-sortable primary key can lead to hotspots and performance issues.

While this package draws inspiration from the original typeid Go package (github.com/jetify-com/typeid-go), it provides multiple ID types:

  • typeid.Sortable is based on UUIDv71 and is k-sortable. Its implementation adheres to the draft standard. The suffix part is encoded in lowercase crockford base32.
  • typeid.Random is also based on UUIDv42 and is completely random. Unlike typeid.Sortable, the suffix part is encoded in uppercase crockford base32.

Please refer to the respective type documentation for more details.

Install

go install github.com/sumup/typeid

Usage

To create a new ID type, define a prefix type that implements the typeid.Prefix interface. Then, define a TypeAlias for your ID type to typeid.Random or typeid.Sortable with your prefix type as generic argument.

Example:

import "github.com/sumup/typeid"

type UserPrefix struct{}

func (UserPrefix) Prefix() string {
    return "user"
}

type UserID = typeid.Sortable[UserPrefix]

userID, err := typeid.New[UserID]()
if err != nil {
    fmt.Println("create user id:", err)
}

fmt.Println(userID) // --> user_01hf98sp99fs2b4qf2jm11hse4

Database Support

ID types in this package can be used with database/sql and github.com/jackc/pgx.

When using the standard library sql, IDs will be stored as their string representation and can be scanned and valued accordingly. When using pgx, both TEXT and UUID columns can be used directly. However, note that the type information is lost when using UUID columns, unless you take additional steps at the database layer. Be mindful of your identifier semantics, especially in complex JOIN queries.

Maintainers


Based on the go implementation of typeid found at: https://github.com/jetify-com/typeid-go by Jetify. Modifications made available under the same license as the original.

Footnotes

  1. https://datatracker.ietf.org/doc/html/rfc9562

  2. https://datatracker.ietf.org/doc/html/rfc4122