Last active
December 12, 2015 00:48
-
-
Save mariocesar/4686137 to your computer and use it in GitHub Desktop.
PostgreSQL, ticketing system to use numbered sequences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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'; -- | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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) | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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