Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Last active December 12, 2015 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariocesar/4686137 to your computer and use it in GitHub Desktop.
Save mariocesar/4686137 to your computer and use it in GitHub Desktop.
PostgreSQL, ticketing system to use numbered sequences
-- returns and update the next value for a named ticket.
CREATE OR REPLACE FUNCTION get_ticket(ticket_name varchar(50)) RETURNS INTEGER AS $$
DECLARE
ticket INTEGER; --
BEGIN
IF EXISTS (SELECT * FROM ticketing_ticket WHERE name = ticket_name FOR UPDATE) THEN
UPDATE ticketing_ticket SET currval = currval + incval
WHERE name = ticket_name RETURNING currval INTO ticket; --
RETURN ticket; --
ELSE
INSERT INTO ticketing_ticket (name)
VALUES(ticket_name) RETURNING currval INTO ticket; --
RETURN ticket; --
END IF; --
END; --
$$ LANGUAGE 'plpgsql'; --
-- Table: ticketing_ticket
CREATE TABLE ticketing_ticket
(
id serial NOT NULL,
name character varying(50) NOT NULL,
currval integer NOT NULL DEFAULT 1,
incval integer NOT NULL DEFAULT 1,
CONSTRAINT ticketing_ticket_pkey PRIMARY KEY (id),
CONSTRAINT ticketing_ticket_name_key UNIQUE (name)
)
$ psql testdb < ticket_table.sql
$ psql testdb < ticket_function.sql
$ psql testdb
psql (9.1.7)
Type "help" for help.
testdb=> select * from get_ticket('ticket1');
ticket
--------
1
(1 row)
testdb=> select * from get_ticket('ticket1');
ticket
--------
2
(1 row)
testdb=> select * from get_ticket('ticket1');
ticket
--------
3
(1 row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment