Skip to content

Latest commit

 

History

35 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

TypeId Pg

An Implementation of TypeId for PostgreSQL

TypeId is a type-safe, globally unique identifier format inspired by Stripe's IDs, designed to be sortable, unique and type-safe.

This implementation of TypeId does some modification to the base TypeId specification by replacing the random UUID part of the TypeId in favor of a sortable ULID

This implement of TypeId consists of two parts a Type prefix and a ULID suffix, separated by an underscore.

  • user_01hxyg96mv7ws0e2kw4zcgp3kz
    └──┘ └────────────────────────┘
    Type          ULID
    
  • Type Prefix

    • The type prefix is a string of up to 63 characters in lowercase snake_case ASCII (a-z and underscore). It indicates the type of entity the TypeId represents (e.g., user, post, etc.). This helps prevent accidental misuse of IDs and aids in understanding the entity type.
  • ULID Suffix

    • Following the underscore is a 26-character string that represents a ULID. This part ensures the TypeId's global uniqueness and this also makes TypeId's sortable.

This implementations TypeId offers a modern and efficient way to handle globally unique identifiers in a type-safe manner, with enhanced sorting capabilities.

Usage of TypeId Pg

Once you've installed the TypeID types and functions from typeid.sql in your Postgres instance, you can use it as follows.

  • Generating TypeId
-- Generate a TypeId
SELECT gen_typeid('user') 
-- Result: user_01hxyg96mv7ws0e2kw4zcgp3kz 
  • Validating TypeId
-- If TypeId is valid
SELECT check_typeid('user_01hxyg96mv7ws0e2kw4zcgp3kz', 'user') 
-- Result: true

-- If TypeId is invalid
SELECT check_typeid('01hxyg96mv7ws0e2kw4zcgp3kz', 'user')
-- Result: false
  • Defining TypeId
-- Creating a users table with TypeId of type `user` as primary key
CREATE TABLE users (
  -- The id is a TypeId with the type of `user`.   
  -- The id also has a default constraint of `gen_typeid` to autogenerated TypeId with the correct type of `user`. 
  -- The id also has a check constraint of `check_typeid` to check if it's a valid TypeId and has the correct type of `user`.
  id TEXT DEFAULT gen_typeid('user') NOT NULL CHECK (check_typeid(id, 'user')) PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT NOT NULL,
  created_at TIMESTAMPTZ DEFAULT now() NOT NULL,
  updated_at TIMESTAMPTZ
);

About

A pure plgsql TypeId generation implementation for PostgreSQL.

Topics

Resources

Stars

3 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages