Ldapnextval

ldapnextval is a shell-accessible interface to the LDAP Modify-Increment Extension (RFC4525).

In short, it is an helper for creating unique identifiers, just like sequences in a SQL database. It relies on POSIX.1 semaphores to avoid concurrency problems and should so compile on any POSIX compliant operating system.

Grab the source!

The ldapnextval source code is available in a Subversion repository:

% svn checkout https://vcs.sigabrt.org/svn/hack/tools/ldapnextval/trunk ldapnextval

How to use?

Create a sequence schema

The Modify-Increment extension requires the attribute to be of type interger. If you want to create a particular object for sequences, create a new schema file like this (replace highlighted components with your PEN and identifiers unused in your schema):

/usr/local/etc/openldap/schema/blogreen.schema
# Attribute Type Definitions

attributetype ( 1.3.6.1.4.1.30843.2.1 NAME 'nextVal'
	DESC 'Next value of the sequence'
	EQUALITY integerMatch
	SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )

# Object Class Definitions

objectclass ( 1.3.6.1.4.1.30843.1.1 NAME 'sequence'
	DESC 'Sequence'
	SUP top STRUCTURAL
	MUST ( cn $ nextVal ) )

You then have to edit slapd configuration file so that it reads your schema:

include		/usr/local/etc/openldap/schema/blogreen.schema

Add sequence objects

Create a sequence in the directory using the following ldif snippet:

dn: cn=test-sequence,dc=blogreen,dc=org
changetype: add
cn: test-sequence
objectClass: top
objectClass: sequence
nextVal: 1

Note that the sequence always has an unused value. The reason of using the next available value instead of the current value is to behave like most RDBMS that cannot be asked the current value of a sequence (Read more about PostgreSQL's Sequence Manipulation Functions).

Advance the sequence

ldapnextval only needs two arguments: the Distinguished Name and the Attribute Name of the item to advance. The program write the sequence number on it's standard output and return 0 on success. If the program was not able to perform the operation, diagnostic messages are written on the error output and the return value is greater than 0.

Using the sequence is so as simple as this:

#!/bin/sh
NEXTVAL=`ldapnextval "cn=test-sequence,dc=blogreen,dc=org" "nextVal"`
if [ $? -gt 0 ]; then
  echo "Unable to advance sequence!" >&2
  exit 1
fi
echo "Got sequence ID #${NEXTVAL}!"

Note for FreeBSD users

POSIX.1 semaphores are not built-in in the GENERIC kernel. You will have to either load the sem.ko module or recompile your kernel with the P1003_1B_SEMAPHORES option set. Refer to sem(4) for further details.

top