place_order(
firstName VARCHAR(200), lastName VARCHAR(200), buyerEmail VARCHAR(200),
buyerPhone VARCHAR(30), book JSONB, freeTicket BOOLEAN, eventDate VARCHAR(20),
eventHour VARCHAR(10), orderTotal NUMERIC(8, 2)
) RETURNS INTEGER AS $$
DECLARE
place RECORD;
_order_id INTEGER;
counter INTEGER;
_show_id INTEGER;
_event_id INTEGER;
_available INTEGER;
_sold INTEGER;
BEGIN
INSERT INTO
purchase (name, surname, phone, email, guest)
VALUES
(firstName, lastName, buyerPhone, buyerEmail, freeTicket)
RETURNING
id INTO _order_id;
FOR place IN SELECT * FROM json_to_recordset(to_json(book)) AS seat (id INTEGER, title TEXT, quantity INTEGER) LOOP
counter := 0;
SELECT
s.id, s.event_id, b.qty_available INTO _show_id, _event_id, _available
FROM
event_shows s,
ticket_books b
WHERE
place.id = b.id AND
s.event_id = b.event_id AND
s.start_date::date = to_date(eventDate, 'DDMMYYYY')::date;
SELECT
COUNT(id) INTO _sold
FROM
ticket
WHERE
book_id = place.id AND
show_id = _show_id AND
showtime = eventHour;
IF
_available - _sold < place.quantity
THEN
ROLLBACK;
RETURN 0;
END IF;
WHILE counter < place.quantity LOOP
counter := counter + 1;
INSERT INTO
ticket (book_id, order_id, show_id, showtime, secret)
VALUES
(place.id, _order_id, _show_id, eventHour, random_string(6));
END LOOP;
END LOOP;
COMMIT;
RETURN _order_id;
END;
$$ LANGUAGE plpgsql;
потому что ф-ции не умеют в контроль транзакций?
Обсуждают сегодня