Random Number Generator

Informix and standard SQL has no built-in random number functions/generators. This small bladelet provides this functionality.

Usage

udr_srand(seed)sets the seed.
udr_get_randmax()returns whatever RAND_MAX is on your system.
udr_rand()returns an integer between 0 and RAND_MAX.
udr_rand_n_m(n, n)returns an integer between n and m.

The Code

[udr_rand.c]
#include <stdlib.h>
#include "mi.h"

void udr_srand(mi_integer seed, MI_FPARAM *fparam)
{
	(void) fparam;

	srand(seed);
}

mi_integer udr_rand(MI_FPARAM *fparam)
{
	(void) fparam;

	return rand();
}

mi_integer udr_get_randmax(MI_FPARAM *fparam)
{
	(void) fparam;

	return RAND_MAX;
}

mi_integer udr_rand_n_m(mi_integer n, mi_integer m, MI_FPARAM *fparam)
{
	int range;

	(void) fparam;

	if	( n == m )
		return n;

	if	( n < m )
		range = 1 + m - n;
	else
	{
		range = 1 + n - m;
		n = m;
	}

	return n + (int) ((double)rand() / ((double)RAND_MAX + 1) * range);
}

Make

To compile the bladelet use the following Makefile

[Makefile]
default : udr_rand.bld

CC = gcc
CFLAGS = -W -Wall -ansi -pedantic -O2
CBLDINCLS = -I${INFORMIXDIR}/incl/public -I${INFORMIXDIR}/incl/esql -I${INFORMIXDIR}/incl
CBLDFLAGS = -DMI_SERVBUILD -fPIC -shared
LDBLDFLAGS = -G
#linux needs: LDBLDFLAGS = -shared -u _etext

RM = rm -f

.SUFFIXES:
.SUFFIXES: .o .c

.c.o:
	${CC} ${CFLAGS} ${CBLDFLAGS} ${CBLDINCLS} -c $<

FILES.c = udr_rand.c

FILES.o = ${FILES.c:.c=.o}

udr_rand.bld: ${FILES.o}
	${LD} ${LDBLDFLAGS} -o $@ ${FILES.o}

clean:
	${RM} ${FILES.o} udr_rand.bld

Register

To register the functions run the following SQL against the required database

[register.sql]
create function udr_get_randmax()
returns integer
with (class="rnd")
external name "$INFORMIXDIR/extend/rnd/udr_rand.bld(udr_get_randmax)"
language c;

create procedure udr_srand(seed integer)
with (class="rnd")
external name "$INFORMIXDIR/extend/rnd/udr_rand.bld(udr_srand)"
language c;

create function udr_rand()
returns integer
with (class="rnd")
external name "$INFORMIXDIR/extend/rnd/udr_rand.bld(udr_rand)"
language c;

create function udr_rand_n_m(n integer, m integer)
returns integer
with (class="rnd")
external name "$INFORMIXDIR/extend/rnd/udr_rand.bld(udr_rand_n_m)"
language c;

VP Class

VPCLASS=rnd