Thursday, June 25, 2015

Use sequence for toggling boolean value

I recently needed to build a postgres function that generated names, the function should return double names half of the times it was called. The function were to be run in a loop in a main function so the first idea was to use a boolean variable in the main function that was sent as a parameter to the name function. The was boolean was toggled after every loop iteration.

A better solution that I came up with is to use a sequence. These are stateful and can be access in the entire scheme.

I create a sequence that counts from 0 to 1 and then starts over. I then cast the result to char and then to boolean.

CREATE SEQUENCE double_first_name_toggle MINVALUE 0 MAXVALUE 1 CYCLE;
SELECT nextval('double_first_name_toggle')::char::boolean into double_first_name;

Every time the SELECT nextval('double_first_name_toggle')::char::boolean into double_first_name; is called it the result is the opposite from last time.

This is now used in the name function and no parameter needs to be sent in.



No comments:

Post a Comment