Please see answer below and Edit#1. However, the trigger still fails under PetaPoco/Npgsql.
I am missing something basic here. I need to ensure that any record added to the table has an orderno given only by the sequence. This should include even when the orderno is being supplied by the insert statement itself. That is,
insert into returntooffice (chart_recid, returndate, torder, **orderno**) values (14982,'2016-11-09','2017-12-4 00:21:42.553508', **0**);
and
insert into returntooffice (chart_recid, returndate, torder) values (14982,'2016-11-09','2017-12-4 00:21:42.553508');
should both result in the next orderno from the sequence and not an orderno of 0. That is, what is actually happening is that the supplied orderno (of 0) is being inserted--not the next sequence value (of 8000). I am using a trigger here since the actual composed insert is by an ORM that does not respect postgreSQL DEFAULT clauses on columns.
Here are the details:
CREATE TABLE returntooffice
(
recid serial NOT NULL,
orderno integer NOT NULL,
chart_recid integer NOT NULL,
returndate date,
torder timestamp without time zone NOT NULL DEFAULT now(),
modified timestamp without time zone DEFAULT now(),
return_as_needed boolean,
is_deferred boolean,
CONSTRAINT returntooffice_pk PRIMARY KEY (recid),
CONSTRAINT returntooffice_chart_fk FOREIGN KEY (chart_recid)
REFERENCES charts (recid) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE RESTRICT,
CONSTRAINT returntooffice_order_unqiue UNIQUE (orderno),
CONSTRAINT returntooffice_unqiue UNIQUE (chart_recid, torder)
)
WITH (
OIDS=FALSE
);
ALTER TABLE returntooffice
OWNER TO postgres;
CREATE TRIGGER get_next_order_number_trigger
BEFORE INSERT
ON returntooffice
FOR EACH ROW
EXECUTE PROCEDURE getnextorderno();
CREATE TRIGGER update_modified
BEFORE UPDATE
ON returntooffice
FOR EACH ROW
EXECUTE PROCEDURE update_modified();
CREATE SEQUENCE order_number_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 6558
CACHE 1;
ALTER TABLE order_number_seq
OWNER TO postgres;
CREATE OR REPLACE FUNCTION getnextorderno()
RETURNS trigger AS
$BODY$
BEGIN
NEW.orderno := nextval('order_number_seq');
Return NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION getnextorderno()
OWNER TO postgres;
Edit#1: Renaming the trigger as suggested below, allows everything to work correctly under pgAdmin, but still fails on PetaPoco Insert. Any ideas why?
CREATE TRIGGER zzz_get_next_order_number_trigger
BEFORE INSERT
ON returntooffice
FOR EACH ROW
EXECUTE PROCEDURE getnextorderno();