short_ids

This Release
short_ids 0.1.0
Date
Status
Stable
Abstract
Generator of short, unique, textual ids
Description
Function to be used as default value, generating random, textual, id
Released By
depesz
License
PostgreSQL
Special Files
Tags

Extensions

short_ids 0.1.0
Generator of short, unique, textual ids

README

Contents

Function to generate, safely, short, textual ids
======================================

This extension provides function:
generate_random_id(text, text, text, int4, text)
which generates new, unused, random, textual id to be used in a table.

It is done by generating random string, of given length, and then
checking if it wasn't used before.

Functions puts safeguards in place to avoid race condition, so it should
be perfectly safe to use.

It can be loaded by any user, as it only uses pl/PgSQL language.


Building and install
--------
Obtain sources:
- from github: https://github.com/depesz/short_ids
- or from PGXN: http://pgxn.org/dist/short_ids/

Run (in top directory):
$ make install

Then, in PostgreSQL you can do:

$ CREATE EXTENSION short_ids;

or:

$ CREATE SCHEMA short_ids;
$ CREATE EXTENSION short_ids WITH SCHEMA short_ids;

Afterwards, you can use provided function (optionally prefixing it with
schema name) as default value for column in a table.

Parameters to generate_random_id function:
- (TEXT) - name of schema that contains the table that will contain data
           with ids generated by function.
- (TEXT) - name of table
- (TEXT) - column name which will contain the ids
- (INT4) - how many characters to try first (if id will be used,
           function will generate longer ids)
- (TEXT) - optional, string with all characters that can be used to
           generate ids. If it is not provided, it defaults to:
           '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

Example
-------
When you created the extension in public, and you create new table, also
in public:

$ create table test (
    id text primary key default generate_random_id( 'public', 'test', 'id', 3 ),
    other text,
    columns timestamptz
);
$ insert into test (other, columns) values ('xx', now()) returning id;

When you created the extension in short_ids schema, the table is in
schema named prod, and you wants ids generated only using lower case
latin letters:

$ create table prod.whatever (
    slug text primary key default short_ids.generate_random_id( 'prod', 'whatever', 'slug', 2, 'abcdefghijklmnopqrstuvwxyz' ),
    x text
);
$ insert into prod.whatever (x) values ('x') returning slug;

-- 
Hubert depesz Lubaczewski
depesz@depesz.com