How to do it...

Execute the following SQL statements as the postgres user to create a function that can generate IDs as we described:

  1. Create the schema to hold shard-related functionality:
        CREATE SCHEMA shard;
  1. Create a sequence to act as an ID generator:
        CREATE SEQUENCE shard.table_id_seq;
  1. Create the function that will generate IDs:
        CREATE OR REPLACE FUNCTION shard.next_unique_id(
          shard_id INT
        )
        RETURNS BIGINT AS
        $BODY$
        DECLARE
          epoch    DATE := '2016-01-01';
          epoch_ms BIGINT;
          now_ms   BIGINT;
          next_id  BIGINT;
        BEGIN
          epoch_ms := floor(
            extract(EPOCH FROM epoch) * 1000
          );
          now_ms := floor(
            extract(EPOCH FROM clock_timestamp()) * 1000
          );
          next_id := (now_ms - epoch_ms) << 22
              | (shard_id << 11)
     | (nextval('shard.table_id_seq') ...

Get PostgreSQL High Availability Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.